2015-12-15 243 views
0

我想寫一個RSA加密軟件工具,每次使用相同的密鑰。這是我到目前爲止。Python的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() 

而且我得到這個代碼「不支持錯誤RSA密鑰格式」的「後的raw_input的關鍵( )」

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) 
+1

這不是一個有效的密鑰。這是一個關鍵對象的字符串表示。 – kichik

+0

如何將字符串轉換爲關鍵對象? – MathMXC

+0

'RSA.importKey(「key string here」)' – kichik

回答

5

首先,<_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) 
+0

我從更新後的代碼中獲得了頂部 – MathMXC

+0

'<_RSAobj @ 0x24b6348 n <1024>,e,d,p,q,u,private>'這不是你的密鑰,只是一個字符串表示。您無法使用此字符串表示重建鍵對象。 – resec

+0

已經提供了生成,存儲,加載和加密的完整代碼。 – resec