首页 / PYTHON / Python中的RSA加密和解密
Python中的RSA加密和解密
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python中的RSA加密和解密,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1945字,纯文字阅读大概需要3分钟。
内容图文
![Python中的RSA加密和解密](/upload/InfoBanner/zyjiaocheng/710/c8826988b57f4ead9059a822def9464e.jpg)
我需要在Python中使用RSA加密和解密的帮助.
我正在创建一个私钥/公钥对,用密钥加密消息并将消息写入文件.然后我正在从文件中读取密文并使用密钥解密文本.
我在解密部分遇到问题.正如您在下面的代码中所看到的,当我输入decrypted = key.decrypt(message)程序正常工作时,解密的消息再次被加密.好像它不是从文件中读取密文.
任何人都可以帮我写这段代码,所以解密从文件中读取密文,然后使用密钥解密密文?
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys
publickey = key.publickey # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open ('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(message)
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
解决方法:
为了使其工作,您需要在解密之前将密钥从str转换为元组(ast.literal_eval函数).这是固定代码:
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key
publickey = key.publickey() # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
内容总结
以上是互联网集市为您收集整理的Python中的RSA加密和解密全部内容,希望文章能够帮你解决Python中的RSA加密和解密所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。