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

Python,Pycrypto,RSA,AES

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

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密钥,试图解密已转换为字符串的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,”)返回类型’tuple’,因此我认为RSA.decrypt()也期望该类型,但是我无法将该类型写入文本文件.因此,当我将其转换为用于写入文件的字符串时,我需要在解密时将其转换回类型为“ tuple”.我怎样才能做到这一点?也许有一种更好的方式可以达到我未曾考虑过的预期结果?

谢谢

解决方法:

使用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.

上一篇:PHP-密码重置安全吗?


下一篇:Swing应用开发实战系列之四:组件内容实时刷新问题