'Failed to decrypt data with Fernet - TypeError: token must be bytes

I'm trying to make simple encrypt/decrypt cli script. I'm getting an error while decoded the encrypted text.

TypeError: token must be bytes

If I use str.encode(textToDecrypt) or bytes(textToDecrypt, 'utf-8') I get:

cryptography.fernet.InvalidToken

from cryptography.fernet import Fernet

fernet = Fernet(myKey)

selectedOption = input('\nSelect an option\n1. Encrypt\n2. Decypt\n')

if selectedOption == '1':
    textToEncrypt = input('\nEnter the text to encrypt\n')
    print(fernet.encrypt(textToEncrypt.encode()))
elif selectedOption == '2':
    textToDecrypt = input('\nEnter the text to decrypt\n')
    print(fernet.decrypt(textToDecrypt).decode())
else:
print('Please select a valid option.')


Solution 1:[1]

The problem was that with every execution of the program, a new key was generated. The problem of bytes was solved with encode, but the key, raises and error.

This is because when you press 1 and encrypt a string, the program ends. Since the key is not stored anywhere, the key is lost.

Now, if you try to decrypt the encrypted message with a new key, it will raise an error.

You can try this:

from cryptography.fernet import Fernet

key = Fernet.generate_key()
fernet = Fernet(key)
while True:
    selectedOption = input('\nSelect an option\n1. Encrypt\n2. Decypt\n3. Generate new key\n4. Quit\n')

    if selectedOption == '1':
        textToEncrypt = input('\nEnter the text to encrypt\n')
        print(fernet.encrypt(textToEncrypt.encode()))
    elif selectedOption == '2':
        textToDecrypt = input('\nEnter the text to decrypt\n')
        print(fernet.decrypt(textToDecrypt.encode()).decode())
    elif selectedOption == '3':
        print("Generating new key...")
        key = Fernet.generate_key()
        fernet = Fernet(key)
        print("New key is generated.")
    elif selectedOption == '4':
        print("Thank you. Bye.")
        break
    else:
        print('Please select a valid option.')

Solution 2:[2]

Here's how I fixed it:

from cryptography.fernet import Fernet

f = Fernet(b'Ues2RwLN7k8CXFj8lV26RTeJxulxDuuu5OyIGfPPyUc=')

selectedOption = input('\nSelect an option\n1. Encrypt\n2. Decypt\n')

if selectedOption == '1':
    textToEncrypt = input('\nEnter the text to encrypt\n')
    encrypted = str(f.encrypt(bytes(textToEncrypt, 'utf-8')), 'utf-8')

    print('\nEncrypted:')
    print(encrypted)
elif selectedOption == '2':
    textToDecrypt = input('\nEnter the text to decrypt\n')
    decrypted = str(f.decrypt(bytes(textToDecrypt, 'utf-8')), 'utf-8')

    print('\nDecrypted:')
    print(decrypted)
else:
    print('Please select a valid option.')

Solution 3:[3]

I would prefer more secure (Only Mac or Linux) sneaky technique:

from cryptography.fernet import Fernet
import base64
def LoadKey():
   r=open(".forgotten", rb)
   return r.read()
   r.close()
print("Step 1: MasterKey Settings")
a=input("Did you already set the MasterKey (Y/N)")
if a=="N":
 print("Then i will generate it for you")
 ar=open(".forgotten", "wb")
 ar.write(Fernet.generate_key())
 ar.close()
else: 
     print("Okay. Then let's encrypt.")
key = Fernet.generate_key()
fernet = Fernet(key)
while True:
    selectedOption = input('\nSelect an option\n1. Encrypt\n2. Decypt\n3. Generate new key\n4. Quit\n')

    if selectedOption == '1':
        textToEncrypt = input('\nEnter the text to encrypt\n')
        print(fernet.encrypt(textToEncrypt.encode()))
        l=open(textToEncrypt+'.key', "wb")
        lk=key
        ll=LoadKey()
        newfern = Fernet(ll)
        l.write(newfern.encrypt(lk))
        del newfern
        l.close()
        del lk
        del ll
    elif selectedOption == '2':
        textToDecrypt = input('\nEnter the text to decrypt\n')
        l=open(textToDecrypt+'.key', "rb")
        ll=LoadKey()
        newfern = Fernet(ll)
        newfern.decrypt(l.read())
        del newfern
        l.close()
        del ll print(fernet.decrypt(textToDecrypt.encode()).decode())
    elif selectedOption == '3':
        print("Generating new key...")
        key = Fernet.generate_key()
        fernet = Fernet(key)
        print("New key is generated.")
    elif selectedOption == '4':
        print("Thank you. Bye.")
        break
    else:
        print('Please select a valid option.')
Uhhh.... This tool is effective against ppl trying to DECRYPT on A MAC OR A LINUX PC.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 vajad57
Solution 3 beksyLolipops