python-如何使用RSA加密和解密AES密钥并存储在文本文件中
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-如何使用RSA加密和解密AES密钥并存储在文本文件中,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2435字,纯文字阅读大概需要4分钟。
内容图文
![python-如何使用RSA加密和解密AES密钥并存储在文本文件中](/upload/InfoBanner/zyjiaocheng/661/201a998f074a4877be9334a0234a3f95.jpg)
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.
内容总结
以上是互联网集市为您收集整理的python-如何使用RSA加密和解密AES密钥并存储在文本文件中全部内容,希望文章能够帮你解决python-如何使用RSA加密和解密AES密钥并存储在文本文件中所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。