John_python
John_python

Reputation: 45

Error cryptography Fernet read token from file

I create the key and I encrypt the message send by user, and store this message in a file and after i try to decrypt this message in the file, but i get this error cryptography.fernet.InvalidToken. I don't use the time for the token and I have also converted in byte after.

My code is:

from cryptography.fernet import Fernet



key = Fernet.generate_key()
f = Fernet(key)



def encry():
    global f
    what = input("What i need to encrypt?")
    what_b = str.encode(what)
    token = f.encrypt(what_b)
    print("key generated")
    print("encrypted")
    file1=open("string.txt", "w")
    file1.write(str(token))
    file1.close()
    file2=open("key.txt", "w")
    file2.write(str(key))
    file2.close()

def decry():
    global f
    print("decrypted")
    file1=open("string.txt", "r").read()
    file_de=str.encode(file1)
    file2=open("de.txt", "w")
    what_d = f.decrypt(file_de)
    file1.close()
    file2.write(str(what_d))
    file2.close()


choose = input("Do you want, encrypt or decrypt?" + " " + "(e/d)")
if choose == "e":
    encry()
elif choose == "d":
    decry()
else:
    print("Nothing to do")

Upvotes: 2

Views: 2838

Answers (1)

abc
abc

Reputation: 11929

The problem comes from the way you write and read the message and the key to and from the files. Indeed, the encrypted text and the keys are not strings, but byte strings and need to be treated in a different way.

In your case, when reading and writing it is enough to specify that you do it in binary mode and you can do it by adding the b flag. See the documentation for more detailed information.

Moreover, in your decrypt you also need to read the key from the file.

def encry():

    key = Fernet.generate_key()
    f = Fernet(key)

    what = "example"
    what_b = str.encode(what)
    token = f.encrypt(what_b)

    with open("string.txt", "wb") as f1, open("key.txt", "wb") as f2:
        f1.write(token)
        f2.write(key)


def decry():
    with open("string.txt", "rb") as f1, open("key.txt", "rb") as f2:
        token = f1.read()
        key = f2.read()

    f = Fernet(key)
    what_d = str(f.decrypt(token),'utf-8') #converting back to string

encry()
decry()

Upvotes: 4

Related Questions