当前位置: 首页 > 知识库问答 >
问题:

Python中的RSA加解密

仉磊
2023-03-14

我需要在Python中使用RSA加密和解密的帮助。

我正在创建一个私钥/公钥对,用密钥加密一条消息,并将消息写入一个文件。然后我从文件中读取密文,并使用密钥解密文本。

谁能帮我写这个代码,让解密从文件中读取密文,然后使用密钥解密密文?

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()

共有1个答案

萧懿轩
2023-03-14

为了使其正常工作,您需要在解密之前将密钥从字符串转换为元组(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公钥对。 它会生成keypair,但是在代码的末尾,它会再次运行ssh-keygen。我不知道为什么这样做。因为,rsa.generate()本身将生成keypair,我们将其导出到两个单独的文件中。为什么需要再次运行ssh-keygen? 下面是代码中的几行: 文件pub将存储公钥,id_rsa将存储来自rsa.generate()函数

  • 如何在Python usomg OpenSSL中执行RSA加密和解密? 我有以下几点:

  • 我们封装了一个RSA 加解密的工具放在 extends 中。首先看看它的文件结构 rsa |-- RSACrypt 加解密主程序 |-- RSACryptBigData 大数据加解密 |-- SignUtil 签名类 |-- rsa_public_key.pem 公钥 |-- rsa_private_key.pem 私钥 RSACrypt API RSAC

  • 所以,接下来我需要的是: 创建用于开发的证书,分别为客户端和服务器获取一个证书 通过从客户端编码并在服务器上解码的API检索密码 现在,我按照这个链接创建了certifiactes。那里的女孩一步一步地给出了如何获得自己签名的证书、将其存放在商店等方面的指导。现在,我有问题的部分是: 真的会有人帮我。

  • 本文向大家介绍python RSA加密的示例,包括了python RSA加密的示例的使用技巧和注意事项,需要的朋友参考一下 RSA加密是一种非对称加密,通常使用公钥加密,私钥解密,私钥签名,公钥验签。 在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,而解密密钥(即秘密密钥)SK是需要保密的.RSA算法通常是先生成一对RSA密钥,其中之一是保密密钥,由用户保存;另一个为公开密钥,可对外公

  • 本文向大家介绍python实现RSA加密(解密)算法,包括了python实现RSA加密(解密)算法的使用技巧和注意事项,需要的朋友参考一下 RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。 今天只有短的RSA钥匙才可能被强力方式解破。到2008年为止,世界上还没有任何可靠的攻击RSA算法的方式。只要其密钥的长度足够长,用RSA加密