Python hashlib:TypeError:对象支持所需的缓冲区 API

问题描述

我正在为类编写客户端/服务器程序,该程序允许客户端使用各种不同的加密技术向服务器发送消息。现在,我正在实施对称加密,当我尝试对在初始密钥分发期间从客户端收到的公钥进行哈希处理时,服务器向我抛出一个错误。我对这些库不是很熟悉,所以我不太确定这个错误的原因是什么。

我的服务器代码

from Crypto.Random import *
from Crypto.PublicKey import RSA
import hashlib

import socket

s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host,port))

c = None
addr = None

s.listen(5)
while True:
   c,addr = s.accept()
   print ('Got connection from',addr)
   break
c.send('You have connected to the server.\nPlease select one of the following communication options by entering the corresponding number.\n1. Public Key Encryption\n2. Symmetric Key Encryption\n3. Digital Signature\n4. Hash'.encode('ascii'))
#receive user option,this will get used in code I add in later
option = c.recv(1024).decode()
#receive and process the public key
pKey = RSA.importKey(c.recv(2048).decode())
#receive the original digest
digest = c.recv(2048).decode()
#hash the received key
hash_object = hashlib.sha1(pKey)
newDigest = hash_object.hexdigest()

if newDigest == digest:
    print("Success")
else:
    print("Failure")

我的客户代码

from Crypto import Random
from Crypto.PublicKey import RSA
import hashlib
import socket

s = socket.socket()
host = socket.gethostname()
port = 12345
inLoop = True

s.connect((host,port))
print(s.recv(1024).decode())
while(True):
    option = input("Select an option: ")
    print(option)
    s.send(option.encode())
    if (option == '1'):
        #Begin handshake
        random = Random.new().read
        key = RSA.generate(1024,random)
        pKey = key.publickey().exportKey()
        hash_object = hashlib.sha1(pKey)
        hex_digest = hash_object.hexdigest()
        #send public key
        s.send(pKey)
        #send digest
        s.send(hex_digest.encode())

    elif(option == 2):
        while(inLoop == True):
            ""
    elif(option == 3):
        while(inLoop == True):
            ""
    elif(option == 4):
        while(inLoop == True):
            ""
    else:
        print("Please enter a valid option.")

s.close()

现在很多事情都没有完成,但我遇到的特定问题是客户端创建了一个公共 RSA 密钥,并对其进行哈希处理,然后将公共密钥和 hex_digest 发送到服务器。服务器接收公钥并将其解码为字符串,然后将其转换为 RSA 密钥,但是一旦我尝试对密钥进行哈希处理,hashlib 就会给我一个错误。当服务器到达 hash_object = hashlib.sha1(pKey) 行时,我收到一个错误TypeError: object supporting the buffer API required

我不确定这是什么意思;我做了很多研究。我不知道如何解决这个问题,但由于某种原因,服务器不会对密钥进行哈希处理。

解决方法

我是个白痴。我在做 hash_object = hashlib.sha1(pKey),但 pKey 是一个 RSA 密钥,而不是一个字符串,所以我需要做 hash_object = hashlib.sha1(pKey.exportKey())