python怎样打开加密的文件_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而不是直接转换为字符串.

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.

标签:pycrypto,encryption,aes,rsa,python

来源: https://codeday.me/bug/20191121/2050503.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值