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?.