0

I am writing an encrypter usng Fernet, and I get the following error:

Traceback (most recent call last):
  File "c:\Users\Arthu\Documents\python\face\other\encrypter\encrypter v2\decrypter v2.py", line 24, in <module>
    contents_decrypted = Fernet(secretkey).decrypt(contents)
  File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\cryptography\fernet.py", line 76, in decrypt
    timestamp, data = Fernet._get_unverified_token_data(token)
  File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\cryptography\fernet.py", line 108, in _get_unverified_token_data
    raise InvalidToken
cryptography.fernet.InvalidToken

Encryption code works fine, but decryption code gives error. Even though I am following a youtube instructional video: https://www.youtube.com/watch?v=UtMMjXOlRQc and nobody in the comments seems to have any problems.

here is my encryption code:

import os
from cryptography.fernet import Fernet

print(os.getcwd())
os.chdir(r'C:\my-directory')
files=[]

for file in os.listdir():
    if file == "encrypter v2.py" or file == "thekey.key":
        continue
    if os.path.isfile(file):
        files.append(file)

print(files)

key = Fernet.generate_key()
with open("thekey.key", "wb") as thekey:
    thekey.write(key)

for file in files:
    with open(file, "rb") as thefile:
        contents = thefile.read()
    contents_encrypted = Fernet(key).encrypt(contents)
    with open(file, "wb") as thefile:
        thefile.write(contents_encrypted)
        
    

here is my decryption code:

import os
from cryptography.fernet import Fernet

print(os.getcwd())

os.chdir(r'C:\my-directory')

files=[]

for file in os.listdir():
    if file == "voldemort.py" or file == "thekey.key" or file == "decrypt.py":
        continue
    if os.path.isfile(file):
        files.append(file)
print(files)

with open("thekey.key", "rb") as key:
    secretkey = key.read()

for file in files:
    with open(file, "rb") as thefile:
        contents = thefile.read()
    
    contents_decrypted = Fernet(secretkey).decrypt(contents)
    with open(file, "wb") as thefile:
        thefile.write(contents_decrypted)

0 Answers0