Created
February 20, 2023 19:27
-
-
Save IvanAdmaers/0fa2a72e00fac4dd9e2cdbf7da94d357 to your computer and use it in GitHub Desktop.
Python 3 Encrypt / Decrypt files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from cryptography.fernet import Fernet | |
def encrypt_or_decrypt_files(dir_path, should_encrypt, key): | |
f = Fernet(key) | |
for filename in os.listdir(dir_path): | |
file_path = os.path.join(dir_path, filename) | |
if os.path.isfile(file_path): | |
with open(file_path, 'rb') as f_in: | |
data = f_in.read() | |
if should_encrypt: | |
data = f.encrypt(data) | |
else: | |
data = f.decrypt(data) | |
with open(file_path, 'wb') as f_out: | |
f_out.write(data) | |
print('Files processed successfully.') | |
dir_path = os.path.abspath('./test_dir2') | |
should_encrypt = True | |
key = b'VCh3rCt98y_x9opOx-X_Oz0iM1og4oSvBjJ5ogC2O9g=' | |
encrypt_or_decrypt_files(dir_path, should_encrypt, key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment