在Python和Swift之间交换加密消息
我需要有一个Python代码和Swift Code Exchange加密消息。
这是我尝试的方法:
- 在回顾
选项之后,我认为一种符号密钥算法可以很好地工作。
在Python(照常)中,它是直接加密和解密
Fernet(key).encrypt(b"mdg") # encrypt
Fernet(key).decrypt(encryptedMsg) # decrypt
:似乎最初是直接的,沿着:
func encrypt(key: String, msg: String) throws -> String {
let data = Data(base64URL: key)!
let symetricKey = try! SymmetricKey(data: d)
let msgUtf8 = msg.data(using: .utf8)!
let sealBox = try! AES.GCM.seal(msgUtf8, using: symetricKey, nonce: nil)
return sealBox.combined.base64EncodedString();
}
但是,我找不到与匹配Python的蕨类植物相匹配的算法。
- chacha
在寻找问题时,我登上了这个惊人的来自Bram的答案来自Bram。非常不幸的是,它仅解决了我问题的一侧:在Python中加密消息并将其解码在Swift中。我还需要反向过程。
如何解决这个问题?
I need to have a python code and a swift code exchange encrypted message.
Here's what I tried:
- Fernet
After a review of the options, I thought that a symetric key algorithm could work well.
In python (as usual), it is straightforward to encrypt and decrypt:
Fernet(key).encrypt(b"mdg") # encrypt
Fernet(key).decrypt(encryptedMsg) # decrypt
In swift, it seemed initially straightforward with something along the lines of:
func encrypt(key: String, msg: String) throws -> String {
let data = Data(base64URL: key)!
let symetricKey = try! SymmetricKey(data: d)
let msgUtf8 = msg.data(using: .utf8)!
let sealBox = try! AES.GCM.seal(msgUtf8, using: symetricKey, nonce: nil)
return sealBox.combined.base64EncodedString();
}
However, I have been unable to find the algorithm in swift matching python's Fernet.
- ChaCha
While searching for the problem, I landed on this amazing answer from Bram. Very unfortunately it only solves one side of my problem : encrypting messages in python and decoding them in swift. I also need the reverse process.
How to solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我们首先需要一种创建安全的随机值以生成IV和键的方法。您还可以使用Cryptokit的
SymmetricKey
生成键并从中提取数据,但是现在,我将使用此功能。然后,我们需要计算AES CBC密文的可能性,可以使用CommonCrypto进行。
以及具有SHA-256哈希功能的HMAC。我建议在此处使用Cryptokit的HMAC实现,但是为了使事情变得简单,我选择了CommonCrypto实施。
这将所有这些融合到以下
示例输出中,
我们可以在Python中使用Cryptography.io的实现来使用它。
To start, we first need a way to create secure random values to generate the IV and keys. You can also generate the keys using CryptoKit's
SymmetricKey
and extract the data from them, but for now, I'll use this function.We then require the possibility to compute the AES CBC ciphertext, which can be done using CommonCrypto.
and the HMAC with the SHA-256 hash function. I recommend using CryptoKit's HMAC implementation here, but to keep things simple, I went with the CommonCrypto implementation.
This brings all of this together into the following
An example output can be
We can use this in python using cryptography.io's implementation