代码应该设置一个服务,侦听来自投票网站的连接。它是一个监听来自外部(客户端)连接的服务器。当客户端连接时,客户端等待发送版本号。一旦我的服务器/侦听器发送了版本号,客户机就会响应一个256字节的块,该块是使用我提供的公钥加密的RSA 2048位。然后必须对该块进行解码,(稍后)我将读取内容。我被卡住了,我无法得到它的解密:
我得到这个:
我代码:开始连接…
connection from ('50.28.6.244', 35338)
发送版本号…
接收加密块
回溯(最近一次调用):
文件" votellistener .py",第97行,
主(private_key)文件" votellistener .py",第49行,在Main
decodedfile = decode_msg(data, privatekey)
文件"voteListener.py",第58行,在decode_msg
ciphertext = cipher.decrypt(msg)
File "C:Python27libsite-packagesCryptoCipherPKCS1_OAEP.py",第227行,在解密
引发ValueError("不正确的解密。")
ValueError: Incorrect decryption.
C: 用户桌面 STEXAS vote>暂停
按任意键继续…
import socket
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from os import path
def Main(privatekey):
host = "0.0.0.0"
port = 8192
version = "VOTIFIER 1.9"
print("starting connection...")
while True:
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
print("connection from %s" % str(addr))
print("sending version number...")
c.send(version)
c.send('n')
print("receiving encrypted block")
data = c.recv(256)
c.close()
s.close()
decodedfile = decode_msg(data, privatekey)
with open("votes.txt", 'wb') as f:
f.write(decodedfile)
print("File writen")
def decode_msg(ciphertext, priv_key):
cipher = PKCS1_OAEP.new(priv_key)
msg = cipher.decrypt(ciphertext)
return msg
def read_private_key():
with open("keysmykey.pem", 'rb') as f:
data = f.read()
key = RSA.importKey(data)
return key
def generate_key_pair():
"""Generates a 2048 bit RSA key pair and saves the keys to disk"""
pair = RSA.generate(2048)
f = open("keysmykey.pem", "wb") # private key
f.write(pair.exportKey('PEM'))
f.close()
pub_key = pair.publickey().exportKey(format='PEM')
keytext = str(pub_key).strip("-----BEGIN PUBLIC KEY-----").strip("-----END PUBLIC KEY-----").replace('n', "")
with open("keyspublic.txt", 'wb') as f: # the plain text public key for providing to server list
f.write(keytext)
with open("keyspublic.pem", 'wb') as f: # public key
f.write(pub_key)
if __name__ == "__main__":
private_key = None
if not path.exists("keysmykey.pem"):
generate_key_pair()
if path.exists("keysmykey.pem"):
private_key = read_private_key()
if private_key is not None:
Main(private_key)
else:
print("Error with Keys... no key was generated or found!")
客户端(我想是Votifier的Java版本)使用RSAES PKCS1 v1.5。使用该方案添加了一个解码方法,并更改了对该方法的调用:
在Main ():
decodedfile = decode_msg_v1_5(data, privatekey)
新方法:def decode_msg_v1_5(ciphertext, privateKey):
""" Should consider using the more robust PKCS1 OAEP. """
sentinel = Random.new().read(256) # data length is 256
cipher = PKCS1_v1_5.new(privateKey)
messagereceived = cipher.decrypt(ciphertext, sentinel)
return messagereceived