python rsa加密一致,Python RSA加密

首先,<_rsaobj n>,e,d,p,q,u,private>不是有效的键,不确定如何获取,但它是键的字符串表示形式,仅作为Python对象,不显示实际的键内容,还请注意,不能使用此字符串表示形式重新生成键对象。

在使用密钥进行RSA加密之前,您应该从诸如文件、在内存中生成等位置导入密钥

所以你应该做的是:key = RSA.importKey(externKey, passphrase=None)

其中externKey是一个字符串,因此您可以用这种方式从密钥文件加载密钥字符串。

或:key = RSA.generate(bits, randfunc=None, progress_func=None, e=65537)

其中bits是密钥的强度,例如2048。

无论哪种方式,您都将返回一个RSA密钥对象(_RSAobj),然后您可以像其他代码一样进行加密。

[编辑]完整代码import Crypto

from Crypto.PublicKey import RSA

#Quick way to generate a new key

private_key = RSA.generate(1024)

#Show the real content of the private part to console, be careful with this!

print(private_key.exportKey())

#Get the public part

public_key = private_key.publickey()

#Show the real content of the public part to console

print(public_key.exportKey())

#Save both keys into some file for future usage if needed

with open("rsa.pub", "w") as pub_file:

pub_file.write(public_key.exportKey())

with open("rsa.pvt", "w") as pvt_file:

pvt_file.write(private_key.exportKey())

#Load public key back from file and we only need public key for encryption

with open('rsa.pub', 'r') as pub_file:

pub_key = RSA.importKey(pub_file.read())

#Encrypt something with public key and print to console

encrypted = pub_key.encrypt('hello world', None) # the second param None here is useless

print(encrypted)

#Load private key back from file and we must need private key for decryption

with open('rsa.pvt', 'r') as pvt_file:

pvt_key = RSA.importKey(pvt_file.read())

#Decrypt the text back with private key and print to console

text = pvt_key.decrypt(encrypted)

print(text)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值