0

So, I have a program that is supposed to connect two machines through TCP sockets. I'm trying to implement encryption with RSA keys, using the 'cryptography' library. But, once I run the code, I get the cryptography.fernet.InvalidTokenerror. here is my code down here, could someone explain to me why I get this error and how to solve it please ?

My code: (client)

import socket
SERVER = "127.0.0.1"
PORT = 2022
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((SERVER, PORT))
client.sendall(bytes("This is from Client",'UTF-8'))

#===[Now, the encryption part]===#

key_file = open("key.key","rb")
key = key_file.read()
f = Fernet(key)

count = 0
while True:
    if count > 0:
        out_data = str(input("|>"))
        tokenOut = f.encrypt(bytes(out_data,'utf-8'))
        print(tokenOut)
        client.sendall(bytes(str(tokenOut),'utf-8'))
        if out_data=='bye':
            break
  
    in_data = bytes(str(client.recv(1024)),'utf-8')
#    print(f"[{count}>   ",in_data,"    <]")
    
    tokenIn = f.decrypt(in_data)
    print("From Server :" ,tokenIn)
    count += 1
client.close()

1 Answers1

0

I haven't tested your code, but my first question would be what data are you sending? If it is over 1024 this will cause it to split over multiple messages this will invalidate your token due to the line here:

in_data = bytes(str(client.recv(1024)),'utf-8')

If you have large data you could try increasing this, for example:

in_data = bytes(str(client.recv(4096)),'utf-8')

As a side note: You are using Fernet which uses AES.

AES symmetric encryption and RSA is asymmetric encryption - more information here: Fernet (symmetric encryption))

Dharman
  • 30,962
  • 25
  • 85
  • 135
Packet
  • 11
  • 4