我正在尝试使用socket和cryptography.fernet库通过本地网络发送加密字符串,但是当收到字节时,它抛出一个“cryptography.fernet.InvalidToken”错误。如果我在一个文件中加密和解密,它确实有效,但如果我在本地或在两台不同的计算机上托管服务器和客户端,它就不起作用。
服务器
import socket
from cryptography.fernet import Fernet
crypt = Fernet('sqcyNL5kz2mxWb1KL2QSZWY-GCERE-scEgWBbvq9CCk=')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((host, port))
s.listen(10)
conn, addr = s.accept()
with conn:
while True:
messageEncrypt = conn.recv(2048)
message = crypt.decrypt(messageEncrypt, None).decode()
print(message)
顾客
import socket
from cryptography.fernet import Fernet
crypt = Fernet('sqcyNL5kz2mxWb1KL2QSZWY-GCERE-scEgWBbvq9CCk=')
message = 'sentence'
messageEncode = message.encode()
messageEncrypt = crypt.encrypt(messageEncode)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
s.sendall(messageEncrypt)
s.close()
客户机对消息进行编码、加密,然后发送消息,客户机接收并解密消息。服务器确实正确地解密并打印消息,但立即崩溃,阻止程序的其余部分运行。
奇怪的是,它有足够的时间在解密后打印,然后崩溃。有人知道为什么会这样吗?
服务器控制台:
sentence
Traceback (most recent call last):
File "E:/Google Drive/School/###/###/python/project/morseSrv.py", line 50, in
message = crypt.decrypt(messageEncrypt).decode()
File "C:\Python\lib\site-packages\cryptography\fernet.py", line 74, in decrypt
timestamp, data = Fernet._get_unverified_token_data(token)
File "C:\Python\lib\site-packages\cryptography\fernet.py", line 92, in _get_unverified_token_data
raise InvalidToken
cryptography.fernet.InvalidToken
Process finished with exit code 1