如何使用pickle将公钥从服务器发送到客户端VIA套接字

时间:2018-04-10 17:06:20

标签: python networking pickle public-key

我需要帮助通过使用pickle的套接字从服务器向客户端发送公钥。我只是通过打开两个命令提示来运行它们,所以我不需要通过网络等发送它,如果它有所作为。只是不确定如何使public_key成为pickle文件并通过套接字发送。

服务器代码:

import socket
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Hash import SHA256
from Crypto.Cipher import DES3
random_generator = Random.new().read
import pickle

def main():
    host = '127.0.0.1'
    port = 5000
    s = socket.socket()
    s.bind((host,port))
    s.listen(1)
    c, addr = s.accept()
    print "Connection from: "+str(addr)
    while True:
        data = c.recv(1024)
        if not data:
            break
    print "from connected user: "+str(data)
    data = str(data)
    #"Step 2 Server says hello and sends the public key certificate."        
    print "Start SSL Handshake"
    print"Press Enter to Generate the key pair."        
    a = raw_input("")
    key = RSA.generate(1024, random_generator)
    public_key = key.publickey()        <----- need to pickle and send to client
    c.send(data)

客户代码:

import socket
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Hash import SHA256
random_generator = Random.new().readdef main():

host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host,port))
#"Step 1 Client says hello."
message = raw_input("-> ")
while message != 'q':
    s.send(message)
    data = s.recv(1024)
    print 'Received the public key from server: (iCrypto.PublicKey.RSA '
    #"Step 3 Client verifies the public key."  <------------ need to recieve / depickle key here
    message = raw_input("-> Press enter to verify the public key.")

1 个答案:

答案 0 :(得分:2)

从开放端口中剔除输出会导致问题(understanding pickle insecurity)。此外,您只需添加一层不需要的复杂性。 RSA._RSAobj.exportKey返回一个bytes对象,该对象可以通过套接字直接发送,也很方便地是RSA.importKey()所需的数据类型。

服务器:

#conn is your socket
conn.send(key.publickey().exportKey(format='PEM', passphrase=None, pkcs=1)) 

客户端:

#you'll need to decide how to determine N: number of bytes received (should be constant for constant size key)
pub_key = RSA.importKey(conn.recv( N ), passphrase=None) 
相关问题