Fernet is a symmetric encryption method designed to provide both confidentiality and authenticity for data. It is implemented in the Python cryptography
library and is widely used for securely encrypting and authenticating messages.
Key Features
• Symmetric Encryption: Fernet uses a single secret key for both encryption and decryption. This key must be kept secret; anyone with access to it can decrypt and forge messages.
• Authenticated Encryption: Fernet not only encrypts data but also ensures its integrity and authenticity. This means that encrypted messages cannot be tampered with or read without the key.
• AES Algorithm: It uses AES (Advanced Encryption Standard) in CBC (Cipher Block Chaining) mode with a 128-bit block size for encryption.
• HMAC for Authentication: Fernet uses HMAC (Hash-based Message Authentication Code) with SHA256 to authenticate the encrypted message, ensuring it has not been altered.
• Initialization Vector (IV): Each encryption operation uses a new, randomly generated IV to ensure security even if the same plaintext is encrypted multiple times.
• Timestamps: Fernet tokens include a timestamp, allowing for token expiration and limiting the validity period of encrypted data.
• Key Rotation: Fernet supports key rotation, allowing you to update keys without losing access to previously encrypted data.
How Fernet Works
1. Inputs: The main inputs are the plaintext message, a 256-bit (32-byte) secret key, and the current timestamp.
2. Encryption: The plaintext is padded (using PKCS #7), then encrypted with AES-CBC using the secret key and a random IV.
3. Authentication: An HMAC is computed over the version, timestamp, IV, and ciphertext to ensure integrity.
4. Token Creation: The encrypted data, IV, timestamp, and HMAC are combined and encoded as a Fernet token, which is URL-safe and can be transmitted over the web.
from cryptography.fernet import Fernet
key = Fernet.generate_key() # Generate a new key
f = Fernet(key)
token = f.encrypt(b"my secret") # Encrypt data
plaintext = f.decrypt(token) # Decrypt data