Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment