Key Rotation with FernetFernet builds on best practice cryptography methods, and allows developers to provide a simple method of encrypting and authenticating. In this case we will create a number of keys, and the decrypt with one of them: |
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/fernet3 from cryptography.fernet import Fernet, MultiFernet 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]) (key1,salt) = get_key(password.encode()) (key2,salt) = get_key(password.encode()) (key3,salt) = get_key(password.encode()) print("Password:\t"+password) print("Key1: ",binascii.hexlify(bytearray(key1))) print("Key2: ",binascii.hexlify(bytearray(key2))) print("Key3: ",binascii.hexlify(bytearray(key3))) cipher_suite=MultiFernet([key1, key2,key3]) cipher_suite = Fernet(key2) cipher_text = cipher_suite.encrypt(val.encode()) cipher=binascii.hexlify(bytearray(cipher_text)) print("\nCipher: ",cipher) plain_text = cipher_suite.decrypt(cipher_text) print("\nPlain text: ",plain_text)
In the following we create three keys, and then encrypt with Key2, and then can decrypt using the collection of keys:
Password: hello Key1: 6a4a50586a593148764b59714b334d426876687a6334476535744d2d4d587a576d5166632d5357566e36593d Key2: 6d62326d525438504862317671574a3266424665587a3545687474496c43414c4633576552526f4156656f3d Key3: 75444c797775695f622d4d5f6a5f5876654a793966654b78534c7a56414d6846746b7271674e446270306f3d Cipher: 67414141414142634638706565715237687746656432766e66782d392d6a61565a447a365066333853764d4f576d58557947493652347a74555762746a794451587a33524b6942733368334948444d7a4c77597875546a314d37436f4339454459413d3d Plain text: hello world
Presentation
The following is an outline presentation [slides]: