Last active
July 28, 2023 22:55
-
-
Save mal1kc/a4c947d08244d36db7d3f41d7e6b42ab to your computer and use it in GitHub Desktop.
encrypt_decrypt_filenames
This file contains hidden or 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
#!/bin/env python3 | |
from cryptography.fernet import Fernet | |
import os | |
def generate_key(): | |
# Generating a random 16-byte key (Base64-encoded) | |
return Fernet.generate_key() | |
def load_key(key_file_path): | |
if os.path.exists(key_file_path): | |
with open(key_file_path, "rb") as key_file: | |
return key_file.read() | |
else: | |
key = generate_key() | |
with open(key_file_path, "wb") as key_file: | |
key_file.write(key) | |
return key | |
def toggle_encrypt_decrypt(key, filename): | |
fernet = Fernet(key) | |
# Check if the filename is already encrypted | |
if filename.startswith("encrypted_"): | |
# Decrypt the filename | |
encrypted_filename = filename[len("encrypted_"):] | |
decrypted_filename = fernet.decrypt(encrypted_filename.encode()).decode() | |
return decrypted_filename | |
else: | |
# Encrypt the filename | |
encrypted_filename = fernet.encrypt(filename.encode()).decode() | |
return "encrypted_" + encrypted_filename | |
def _bytes_to_str(variable): | |
if type(variable) is str: | |
return variable | |
return variable.decode() | |
def main(): | |
key_file_path = "./encryption_key.key" | |
key = load_key(key_file_path) | |
for file in os.listdir(os.getcwd()): | |
if file.endswith('.key') or file.endswith('.py'): | |
continue | |
dst = toggle_encrypt_decrypt(key, file) | |
os.rename(file, dst) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment