xxxxxxxxxx
import os
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
password = b"super_secret_password"
salt = os.urandom(16)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256,
iterations=100000,
length=32,
salt=salt,
backend=default_backend()
)
key = base64.urlsafe_b64encode(kdf.derive(password))
cipher = Fernet(key)
# Encrypt the file
with open("file.txt", "rb") as f:
data = f.read()
cipher_text = cipher.encrypt(data)
with open("file.txt", "wb") as f:
f.write(cipher_text)
xxxxxxxxxx
# encrypting
from cryptography.fernet import Fernet
message = "my deep dark secret".encode()
f = Fernet(key)
encrypted = f.encrypt(message)
# decrypting
from cryptography.fernet import Fernet
encrypted = b"...encrypted bytes..."
f = Fernet(key)
decrypted = f.decrypt(encrypted)
xxxxxxxxxx
from cryptography.fernet import Fernet
message = "my deep dark secret".encode()
f = Fernet(key)
encrypted = f.encrypt(message)
xxxxxxxxxx
import hashlib
print(hashlib.sha256(b'key').hexdigest())
#OUTPUT: 2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683
xxxxxxxxxx
from cryptography.fernet import Fernet
data = 'Hello World!'
key = Fernet.generate_key()
fernet = Fernet(key)
EncryptedData = fernet.encrypt(data)
print(EncryptedData)
DecryptedData = fernet.decrypt(EncryptedData).decode()
print(DecryptedData)
xxxxxxxxxx
File? data2.txt
Key? key.csv
Why did you not like Python?
I just find it too constricting.
Wyh ddi yuo ntoelkit yP?hnoj
I utsdfni ti tooscnoctirgtni .