当前位置:  开发笔记 > 编程语言 > 正文

Python RSA加密

如何解决《PythonRSA加密》经验,为你挑选了1个好方法。



1> resec..:

首先,<_RSAobj @0x24b6348 n<1024>,e,d,p,q,u,private>它不是一个有效的密钥,不知道你是如何得到它的,但它是一个字符串表示你的密钥Python只作为一个对象,实际的密钥内容没有呈现,还要注意你不能用这个字符串表示重建密钥对象.

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

所以你应该做的是:

key = RSA.importKey(externKey, passphrase=None)

其中externKey是String,因此您可以使用这种方式从密钥File加载密钥字符串.

或者:

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

在哪里bits是你的钥匙的力量,例如2048.

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

[编辑]完整代码

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)

推荐阅读
360691894_8a5c48
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有