我想獲得2個程序通過網絡使用公共密鑰共享加密數據,但我堅持一個難題:共享信息(密鑰和/或加密的數據)似乎被修改。我希望保持加密數據格式以及密鑰的格式儘可能簡單,以便與其他語言兼容。 爲了解決這個問題,我創建了2個程序:Keyreceive和Keysend。 他們執行順序是:Python - Pycrypto - 通過網絡發送加密數據
- Keyreceive啓動,並等待接收加密的數據
- Keysend啓動,並生成一個RSA密鑰,保存導出的私鑰文件
- Keysend加密一塊數據並將其發送到Keyreceive通過網絡
- Keyreceive進口來自同一個文件的私有密鑰,並用它來解密加密的數據
- Keysend也對加密數據進行驗證的結果
Keysend.py
import socket
import os
from Crypto.PublicKey import RSA
from Crypto import Random
rng = Random.new().read
RSAkey = RSA.generate(1024, rng)
privatekey = RSAkey
publickey = RSAkey.publickey()
print(privatekey.exportKey()) #export under the 'PEM' format (I think)
print(publickey.exportKey())
file = open("Keys.txt", "w")
file.write(privatekey.exportKey()) #save exported private key
file.close()
data = "hello world"
enc_data = publickey.encrypt(data, 16) #encrypt message with public key
print(str(enc_data))
host = "localhost"
port = 12800
connexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connexion.connect((host, port))
connexion.send(str(enc_data)) # send encrypted data, this appears to be the source of the problem
dec_data = RSAkey.decrypt(enc_data) # test decryption
print(dec_data)
os.system("pause")
Keyreceive.py
import socket
import os
from Crypto.PublicKey import RSA
from Crypto import Random
host = ''
port = 12800
connexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connexion.bind((host, port))
connexion.listen(5)
clientconnexion, connexioninfo = connexion.accept()
enc_data = clientconnexion.recv(1024) # receive encrypted data
print(enc_data)
file = open("Keys.txt", "r")
privatestr = file.read() # retrieve exported private key from file
file.close()
print(privatestr)
privatekey = RSA.importKey(privatestr) # import private key
data = privatekey.decrypt(enc_data) # decrypt sent encrypted data
print(data)
os.system("pause")
後兩個文件都完成解密所述加密的數據,Keysender輸出原始消息: 「世界你好」,而Keyreceiver輸出亂碼。 如果加密數據和密鑰格式中存在「隱藏」信息,是否有某種方式可以用「純」文本格式編寫它們?
帶私鑰的文件如何安全傳輸?你意識到這是絕望的不安全?而不是SSL? – EJP