Skip to content

Instantly share code, notes, and snippets.

@derekantrican
Created November 15, 2022 23:51
Show Gist options
  • Save derekantrican/9efa0ffcc26f16cd27d5e3b7c051024a to your computer and use it in GitHub Desktop.
Save derekantrican/9efa0ffcc26f16cd27d5e3b7c051024a to your computer and use it in GitHub Desktop.
Encrypt or Decrypt a file using a password in python
from cryptography.fernet import Fernet
import base64, hashlib
def gen_fernet_key(passcode) -> bytes: # Modified from https://stackoverflow.com/a/72758959/2246411
hlib = hashlib.md5()
hlib.update(bytes(passcode, 'utf-8'))
return base64.urlsafe_b64encode(hlib.hexdigest().encode('latin-1'))
def encrypt_file(target_file, fernet): # https://www.geeksforgeeks.org/encrypt-and-decrypt-files-using-python/
with open(target_file, 'rb') as file:
original = file.read()
encrypted = fernet.encrypt(original)
with open(target_file, 'wb') as encrypted_file:
encrypted_file.write(encrypted)
def decrypt_file(target_file, fernet): # https://www.geeksforgeeks.org/encrypt-and-decrypt-files-using-python/
with open(target_file, 'rb') as enc_file:
encrypted = enc_file.read()
decrypted = fernet.decrypt(encrypted)
with open(target_file, 'wb') as dec_file:
dec_file.write(decrypted)
password = "your_password"
key = gen_fernet_key(password)
fernet = Fernet(key)
target_file = "path_to_file"
encrypt_file(target_file, fernet)
# decrypt_file(target_file, fernet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment