python - 如何使用 RSA 加密和解密 AES key 并将其存储在文本文件中

标签 python encryption aes rsa pycrypto

Python、Pycrypto、RSA、AES

我正在尝试实现一个脚本,该脚本将使用随机生成的 AES key 加密文件,然后使用 RSA 公钥加密所述 AES key 。加密的 AES key 将与拥有私钥的授权人员共享以对其进行解密。代码如下:

from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from Crypto import Random

RSAkey = '-----BEGIN PUBLIC KEY-----\nSome RSA Key here\n-----END PUBLIC KEY-----'

RSAkey = RSA.importKey(RSAkey)

key = Random.new().read(32)

enc_key = RSAkey.encrypt(key, '')

enc_key = str(enc_key)

custom_writefile_function('enc_key.txt', enc_key)

我正在将 enc_key 转换为字符串,以便将其写入文本文件,否则 enc_key.txt 将包含垃圾。然而,问题在于,在另一个脚本中,用于解密 enc_key 以获取用于加密文件的原始 AES key ,尝试解密已转换为字符串的 enc_key 会产生错误:

RSAkey.decrypt(str(RSAkey.encrypt(key, ''))) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/dist-packages/Crypto/PublicKey/RSA.py", line 174, in decrypt return pubkey.pubkey.decrypt(self, ciphertext) File "/usr/lib/python2.7/dist-packages/Crypto/PublicKey/pubkey.py", line 93, in decrypt plaintext=self._decrypt(ciphertext) File "/usr/lib/python2.7/dist-packages/Crypto/PublicKey/RSA.py", line 237, in _decrypt cp = self.key._blind(ciphertext, r) ValueError: Message too large

代码如下:

RSAkey = custom_readfile_function('private_key.txt', 'r')
RSAkey = RSA.importKey(RSAkey)

enc_key = custom_readfile_function('enc_key.txt', 'r')

aes_key = RSAkey.decrypt(enc_key)

custom_writefile_function('key.txt', str(aes_key), 'w')

我认为问题是类型不匹配。 RSAkey.encrypt(key, '') 返回类型“元组”,所以我认为 RSA.decrypt() 也需要这种类型,但我不能将该类型写入文本文件。因此,当我将其转换为用于写入文件的字符串时,我需要在解密时将其转换回类型“元组”。我怎样才能做到这一点?或者也许有更好的方法来实现我没有考虑过的预期结果?

谢谢

最佳答案

使用 base 64 而不是直接转换为字符串。

当心the documentation of the encrypt method您正在使用:

Returns: A tuple with two items. The first item is the ciphertext of the same type as the plaintext (string or long). The second item is always None. Overrides: pubkey.pubkey.encrypt

此外,您应该注意以下建议:

Attention: this function performs the plain, primitive RSA encryption (textbook). In real applications, you always need to use proper cryptographic padding, and you should not directly encrypt data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules Crypto.Cipher.PKCS1_OAEP or Crypto.Cipher.PKCS1_v1_5 instead.

关于python - 如何使用 RSA 加密和解密 AES key 并将其存储在文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25816942/

相关文章:

python - django返回每个用户的最新记录

python - 让父函数返回 - super 返回?

python - 你能在 gif 中显示一些动画循环后的静态图像吗?

c# - 使用 seckeygeneratepair 中的公钥进行加密

php - 如何保证 mySQL 数据库的安全?

ios - 在IOS上对图像进行加密/解密

java - 基于身份的加密和开源

python - 在 Python 中循环 excel 工作表和行

java - 错误填充异常 : pad block corrupted

c# - 如何使用 PEM 文件中的 rsa 解密