我正在制作一个实现Diffie-Hellman算法的客户端 - 服务器程序
客户:
from __future__ import print_function
import math
import socket
host = "localhost"
port = 1200
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected with Server")
sharedPrime = 23 # p
sharedBase = 5 # g
aliceSecret = 6 # a
s.send(bytes(aliceSecret))
bobSecret=s.recv(1024)
# Alice Sends Bob A = g^a mod p
A = (sharedBase**aliceSecret) % sharedPrime
s.send(bytes(A))
B=s.recv(1024)
B=B.decode()
# Alice Computes Shared Secret: s = B^a mod p
aliceSharedSecret = (int(B)** aliceSecret) % sharedPrime
print( "Alice Shared Secret: ", aliceSharedSecret )
服务器代码基本相同,只是它处理算法的“Bob”方面。我的问题从这一行开始:
aliceSharedSecret = (int(B)** aliceSecret) % sharedPrime
这给了我这个错误:
invalid literal for int() with base 10: '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
我回去看看“B”到底是什么,它只是空白。我究竟做错了什么?
看看这一行:
s.send(bytes(aliceSecret))
你在这里将int
值转换为bytes
。这会产生像b'\x00\x00\x00\x00\x00\x00'
这样的结果,即使在解码之后也不能直接转换为int
,因为它不是十进制形式的数字。有两种可能的解决方案:
1)正确解码值,该行将bytes
对象解释为int
分割成字节:
B = int.from_bytes(B, byteorder='big', signed=False) # instead of B = B.decode()
2)在转换为int
之前将原始的str
值转换为bytes
,以便后转换可以工作