我已经设法使用python套接字将具有python程序的文件从一台计算机发送到另一台计算机,每台计算机上的python代码相同。我遇到的问题是加密部分,我似乎找不到找到加密文件,发送文件然后解密的方法。我正在使用Fernet进行加密,但是第二台计算机上的解密程序却给我“ raise InvalidSignature(“签名与摘要不匹配。”) cryptography.exceptions.InvalidSignature:签名与摘要不匹配。”。那么我该如何加密某些东西,将其发送到另一台计算机,然后再对其进行解密?
server.py
from cryptography.fernet import Fernet
import socket
fernet_key = Fernet.generate_key()
f = open('fernet_key.txt', 'w+')
f.write(str(fernet_key.decode()))
def fernet_encryption(message='NoMessagePassedToEncryption'):
cipher_suite = Fernet(fernet_key)
cipher_text = cipher_suite.encrypt(message.encode()).decode()
return cipher_text
def fernet_decryption(message='NoMessagePassedToDecryption'):
cipher_suite = Fernet(fernet_key)
decrypted_cipher_msg = cipher_suite.decrypt(message.encode()).decode()
return decrypted_cipher_msg
print('Server started!')
print('Waiting for clients...')
s = socket.socket()
s.bind(('127.0.0.1', 5555))
s.listen(10)
c, addr = s.accept()
f = open('file.pdf', 'wb')
first = True
file_length = 0
counter = 0
while True:
msg = c.recv(1024)
print('Encrypted: ' + str(msg))
msg = fernet_decryption(msg.decode())
print('Decrypted: ' + str(msg))
if first:
file_length = msg
first = False
else:
if msg == b'':
break
else:
f.write(msg)
counter += 1
f.close()
c.close()
s.close()
client.py
from cryptography.fernet import Fernet
import socket
import os
get_key = open(os.getcwd() + '/' + 'fernet_key.txt', 'rb')
fernet_key = get_key.read().decode()
get_key.close()
def fernet_encryption(message='NoMessagePassedToEncryption'):
cipher_suite = Fernet(fernet_key)
cipher_text = cipher_suite.encrypt(message.encode()).decode()
return cipher_text
def fernet_decryption(message='NoMessagePassedToDecryption'):
cipher_suite = Fernet(fernet_key)
decrypted_cipher_msg = cipher_suite.decrypt(message.encode()).decode()
return decrypted_cipher_msg
if os.path.exists(file_dir):
length = os.path.getsize(file_dir)
n_pac = (length / 1024)
print('n_pac: ' + str(n_pac))
length = fernet_encryption(length)
s.send(length.encode())
print(length)
with open(file_dir, 'rb') as infile:
data = infile.read(1024)
print(data)
data = fernet_encryption(data)
print('Encrypted: ' + str(data))
data = data.encode()
while data:
s.send(data)
data = infile.read(1024)
s.close()
f.close()
在服务器上导致此错误
raise InvalidToken
cryptography.fernet.InvalidToken