Skip to content

Instantly share code, notes, and snippets.

@LordGhostX
Last active July 23, 2023 13:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LordGhostX/53fd6666dc395cbb33b2f8a3cf67fc71 to your computer and use it in GitHub Desktop.
Save LordGhostX/53fd6666dc395cbb33b2f8a3cf67fc71 to your computer and use it in GitHub Desktop.
Fernet Symmetrical Encryption Implementation
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.fernet import Fernet
def encrypt_text(text, salt):
def generate_key(master, salt):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA512(),
length=32,
salt=salt.encode(),
iterations=100,
backend=default_backend()
)
key = base64.urlsafe_b64encode(kdf.derive(master.encode()))
return key
key = generate_key(text, salt)
encryptor = Fernet(key)
hash = encryptor.encrypt(text.encode())
return hash.decode(), str(key)[2:-1]
def decrypt_text(hash, key):
decryptor = Fernet(key)
text = decryptor.decrypt(hash.encode())
return text.decode()
@UkiDLucas
Copy link

UkiDLucas commented Jul 23, 2023

Thank you!
It would be even nicer if you showed how to save the key as a string for saving and sending and then re-constitute that string to the key on the decrypt side.

def decrypt_text(hash, key_text):
    key = bytes(saved_text, 'utf-8')
    decryptor = Fernet(key)
    text = decryptor.decrypt(hash.encode())
    return text.decode()

# usage:

saved_text = "I41_sE8EtPvzb8-XooyiuG4KF_-AuGBDYQNvryTP0BY="
decrypted = decrypt_text(hash, saved_text)
print("decrypted: ", decrypted)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment