1

I created two .py, one for encryption and one for decryption. Here they are.

Encryptor.py

import os
from cryptography.fernet import Fernet

files = []

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

key= Fernet.generate_key()

with open("thekey.key","wb") as keygen:
    keygen.write(key)

for file in files:
    with open(file,"rb") as openedfile:
        content=openedfile.read()
        encrypt_content = Fernet(key).encrypt(content)
    with open(file,"wb") as arch:
        arch.write(encrypt_content)

Decrypt

import os
from cryptography.fernet import Fernet
files = []
key=None

for file in os.listdir():
    if file == "encryptor.py" or file == "decryptor.py" or file =="thekey.key":
        pass
    if os.path.isfile(file):
        files.append(file)

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


for file in files:
    with open(file,"rb") as openedfile:
        content1=openedfile.read()
        decrypted_content = Fernet(key).decrypt(content1)
    with open(file,"wb") as arch:
        arch.write(decrypted_content)

it decrypts all the files that were encrypted, but it raises this exception

Traceback (most recent call last):
  File "C..decryptor.py", line 19, in <module>
    decrypted_content = Fernet(key).decrypt(content1)
  File "C..\venv\lib\site-packages\cryptography\fernet.py", line 83, in decrypt
    timestamp, data = Fernet._get_unverified_token_data(token)
  File "C..\venv\lib\site-packages\cryptography\fernet.py", line 115, in _get_unverified_token_data
    raise InvalidToken
cryptography.fernet.InvalidToken

Am I doing something wrong? Is the encrypted text different, and for that reason it is an invalid token in some way?.

  • 1
    Try printing the encrypted data to the console and verify that the file also contains this data. It may be an issue with encoding schemes. – Khalil Jul 15 '22 at 01:33
  • I'd expect a hidden file to be in there or something like that. Print out the filenames that are handled. – Maarten Bodewes Jul 15 '22 at 21:33

0 Answers0