Cryptography in Python
Jump to navigation
Jump to search
Internal
Organizatorium
Symmetric Cryptography
requirements.txt:
cryptography == 3.4.7
NOT TESTED:
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
def init_fernet(password):
key = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=b'some-salt',
iterations=1000, backend=default_backend()).derive(password)
return Fernet(base64.urlsafe_b64encode(key))
# encrypt
password = ...
clear_data = ...
encrypted_file_path=....
cypher_data = init_fernet(password.encode('utf-8')).encrypt(clear_data)
with open(encrypted_file_path, mode='wb') as f:
f.write(cypher_data)
# decrypt
clear_data_2 = init_fernet(password.encode('utf-8')).decrypt(cypher_data)