Last active
July 23, 2023 13:53
-
-
Save LordGhostX/53fd6666dc395cbb33b2f8a3cf67fc71 to your computer and use it in GitHub Desktop.
Fernet Symmetrical Encryption Implementation
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
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
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.