3

我试图让 2 个程序使用公钥在网络上共享加密数据,但我遇到了一个难题:共享的信息(密钥和/或加密数据)似乎被修改了。我希望保持加密数据格式以及密钥格式尽可能简单,以便与其他语言兼容。为了解决这个问题,我创建了 2 个程序:Keyreceive 和 Keysend。他们按以下顺序执行:

  1. Keyreceive 启动并等待接收加密数据
  2. Keysend 启动并生成 RSA 密钥,将导出的私钥保存到文件中
  3. Keysend 加密一段数据并通过网络将其发送到 Keyreceive
  4. Keyreceive 从同一文件中导入私钥,并使用它来解密加密数据
  5. 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")

密钥接收.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 输出原始消息:“hello world”,而 Keyreceiver 输出乱码。如果加密数据和密钥格式中存在“隐藏”信息,是否有某种方法可以将它们写入“纯”文本格式?

4

1 回答 1

5

你是对的,哪条线是问题的根源。

connexion.send(str(enc_data))

enc_data这是一个元组,它的第一个(实际上也是唯一的)元素是一个包含实际密文的字符串。当您调用str它时,您会得到 Python 将元组转换为字符串的尝试,这不是您想要的。如果你把它改成这样:

connexion.send(enc_data[0])

那么它应该做你想做的事。

于 2011-07-30T22:20:43.330 回答