We can use Fernet from the cryptography module in Python to encrypt and decrypt data securely. The Fernet module uses a symmetric-key encryption algorithm to encrypt and decrypt data. So, if we use a secret key to encrypt plaintext, we would need to use the same secret key to decrypt the ciphertext.
As per the specification of Fernet, it uses:
- AES encryption algorithm in CBC mode
- 128-bit secret key
- PKCS7 padding
- 128-bit Initialization Vectors (IV) that are generated using os.urandom() (How to generate cryptographically secure random numbers in Python?)
And, after encryption, Fernet generates a token that has the following format:
Version | Timestamp | IV | Ciphertext | HMAC
Version – It is an 8-bit field that specifies the version being used. Currently, it uses the value 128 or 0x80
Timestamp – It is a 64-bit value that specifies the timestamp when the token was created.
IV – It is a 128-bit Initialization Vector that is generated using os.urandom()
Ciphertext – This field specifies the ciphertext and can be multiple of 128-bit in size.
HMAC – This is a 256-bit field. The concatenation of Version, Timestamp, IV, and Ciphertext is taken as input and the SHA256 HMAC algorithm (How does HMAC algorithm work?) is used to generate the output.
How to encrypt and decrypt data using Fernet in Python?
We can use Fernet to encrypt and decrypt data in the following way:
0 Comments