Python:ValueError:int()的基数为10的无效文字:'\ x00

问题描述 投票:0回答:1

我正在制作一个实现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”到底是什么,它只是空白。我究竟做错了什么?

python-3.x client-server diffie-hellman
1个回答
0
投票

看看这一行:

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,以便后转换可以工作

© www.soinside.com 2019 - 2024. All rights reserved.