Cryptography in Python: Difference between revisions
Jump to navigation
Jump to search
(One intermediate revision by the same user not shown) | |||
Line 24: | Line 24: | ||
password = ... | password = ... | ||
clear_data = ... | clear_data = ... | ||
encrypted_file_path=.... | |||
cypher_data = init_fernet(password.encode('utf-8')).encrypt(clear_data) | 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 | # decrypt | ||
clear_data_2 = init_fernet(password.encode('utf-8')).decrypt(cypher_data) | clear_data_2 = init_fernet(password.encode('utf-8')).decrypt(cypher_data) | ||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 05:40, 1 June 2022
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)