I want to decrypt many files and it's working perfectly (encrypt, decrypt).
My problem is that, if any file exists which is not is encrypted, I get an "invalidToken" error message, and the program is unable to decrypt the remaining encrypted files.
Here is my code
import os
from cryptography.fernet import Fernet
import sys
import warnings
InvalidToken = False
key = b'SpecialKindKey'
fernet = Fernet(key)
encr_file_list = []
path ="C:/users/NineTail/desktop/pokemon/go/"
#we shall store all the file names in this list
filelist = []
for root, dirs, files in os.walk(path):
for file in files:
#append the file name to the list
filelist.append(os.path.join(root,file))
#print all the file names
for name in filelist:
print(name)
for file in filelist:
with open(file, 'rb') as f:
file_content = f.read()
decrypted_content = fernet.decrypt(file_content)
with open(file, 'wb') as f:
f.write(decrypted_content)
Error message :
Traceback (most recent call last):
File "r3.py", line 36, in <module>
decrypted_content = fernet.decrypt(file_content)
File "C:\Program Files\Python38\lib\site-packages\cryptography\fernet.py", line 85, in decrypt
timestamp, data = Fernet._get_unverified_token_data(token)
File "C:\Program Files\Python38\lib\site-packages\cryptography\fernet.py", line 121, in _get_unverified_token_data
raise InvalidToken
cryptography.fernet.InvalidToken
CodePudding user response:
Use try/except
to try to decrypt. If decrypting fails, continue without writing.
...
from cryptography.fernet import Fernet, InvalidToken
...
for file in filelist:
with open(file, 'rb') as f:
file_content = f.read()
try:
decrypted_content = fernet.decrypt(file_content)
except InvalidToken:
continue
with open(file, 'wb') as f:
f.write(decrypted_content)
...
CodePudding user response:
Perhaps try having a loop that repeats the number of times of files you have, and calls each file separately from the rest
Define a list of files, and store that in a variable say:
num = #number of files
files = [file1.txt,file2.txt]
For i in range(num):
files[num] = open(item, 'r')
num = 1