[英]Python RSA encryption
我正在嘗試編寫RSA加密軟件工具,該工具每次都會使用相同的密鑰。 這是我到目前為止所擁有的。
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
key = <_RSAobj @0x24b6348 n<1024>,e,d,p,q,u,private>
publickey = key.publickey()
encrypted = publickey.encrypt('hi', 32)
print(encrypted)
我在第5行指向<符號的地方出現語法錯誤。 我知道這是有效的私鑰。 有什么問題以及如何解決。 我也在用python 2.7.3
[編輯]我從此代碼中獲取了密鑰
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import os
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
print(key)
raw_input()
另外,我在“ raw_input()”之后從此代碼中得到“不支持RSA密鑰格式的錯誤”
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
text_file = open("keyfile.txt", "w")
text_file.write('<_RSAobj @0x24b6348 n<1024>,e,d,p,q,u,private>')
text_file.close()
raw_input()
with open('keyfile.txt', 'r') as f:
externKey = f.readline()
key = RSA.importKey(externKey, passphrase=None)
publickey = key.publickey()
encrypted = publickey.encrypt('hi', 32)
print(encrypted)
首先, <_RSAobj @0x24b6348 n<1024>,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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.