Fernet with PBKDF2Fernet builds on best practice cryptography methods, and allows developers to provide a simple method of encrypting and authenticating. Overall it uses 128-bit AES symmetric encryption in a CBC mode with PKCS7 padding and HMAC using SHA256 for authentication. Note: It may take a few seconds to generate, so please wait for the results. Generate an example and use the decrypt page: [Fernet Decrypt] |
Outline
The token has a version number, a time stamp, the IV, the cipher text and an HMAC signature:
- Version: 8 bits
- Timestamp: 64 bits (the number of seconds since between January 1, 1970 UTC and the time of the encryption).
- IV: 128 bits
- Ciphertext - variable length: Multiple of 128 bits
- HMAC: 256 bits
Code
Fernet is used to define best practice cryptography methods, and Harmat supports core cryptographical primitives. This version uses PBKDF2 to generate a hash of a key with salt:
# https://asecuritysite.com/encryption/fernet2 from cryptography.fernet import Fernet from cryptography.hazmat.primitives import hashes from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC import sys import binascii import base64 import os password="hello" val="hello world" def get_key(password): salt = os.urandom(16) kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),length=32,salt=salt,iterations=100,backend=default_backend()) key=base64.urlsafe_b64encode(kdf.derive(password)) return (key,salt) if (len(sys.argv)>1): val=sys.argv[1] if (len(sys.argv)>2): password=str(sys.argv[2]) (key,salt) = get_key(password.encode()) print("Password:\t",password) print("Key: ",binascii.hexlify(bytearray(key))) print("Salt:\t",binascii.hexlify(salt)) cipher_suite = Fernet(key) cipher_text = cipher_suite.encrypt(val.encode()) print("\nCipher: ",binascii.hexlify(bytearray(cipher_text))) print("\nVersion:\t",cipher_text[0:2]) print("Time stamp:\t",cipher_text[2:18]) print("IV:\t\t",cipher_text[18:50]) print("HMAC:\t\t",cipher_text[-64:]) plain_text = cipher_suite.decrypt(cipher_text) print("\nPlain text: ",plain_text)
A sample run is:
Password: hello Key: 354f6a656d5a4950446848785171546f77633470634134636a6d61314d6e68713357426673516672624b553d Salt: 114647c5fb0cf0f7dffe1e8b74da4967 Cipher: 6741414141414263463762506f49727947684d77714377467175324d57754c4f4d6756514e53664f36504f54335f436239594d74716265517565426954367a6e326e426a5649624a5472656e6a6f3336754f317063364872386973587a7652774b413d3d Version: 67 Time stamp: 4141414141426346 IV: 3762506f49727947684d777143774671 Cipher: 75324d57754c4f4d6756514e53664f36504f54335f436239594d74716265517565426954367a6e326e426a HMAC: 5649624a5472656e6a6f3336754f317063364872386973587a7652774b413d3d Plain text: hello world
Presentation
The following is an outline presentation [slides]: