cryptography package in Python provides tools to encrypt
byte using a key. The same key that encrypts is used to decrypt, which is
why they call it symmetric encryption. Fernet is an encryption spec
that utilizes AES-128 under the hood with HMAC and some other additions.
If you need to encrypt and decrypt some data using Python, this is a very easy
way to do it.
Install cryptography package
Check out the cryptography documentation for more details, but all you need to do is run pip install:
python -m pip install cryptography
Encrypt and decrypt
The example below demonstrates how to:
- Generate a key with static method
- Instantiate an instance of the
- Encrypt data with
- Decrypt data with
Be sure to store the key and keep it secure. You can not generate the same key again and if you do not save it after generating it, you will lose it forever. Also keep it secure since anyone who has access to it can decrypt your data.
# pip install cryptography from cryptography.fernet import Fernet """ Important things remember: - Save the key! - Protect the key! - Only share the key with people who should have access to the data! - Only share the key using secure methods! (if you need to share it at all) """ # Encrypt key = Fernet.generate_key() # Keep this secret! print(type(key)) # bytes print(key) # base64 encoded 32 bytes my_fernet = Fernet(key) encrypted_bytes = my_fernet.encrypt(b"Hello, world!") print(encrypted_bytes) # Decrypt clear_text = my_fernet.decrypt(encrypted_bytes) print(clear_text)
Here is the output from an example run in the interpreter:
$ python Python 3.8.1 (v3.8.1:1b293b6006, Dec 18 2019, 14:08:53) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from cryptography.fernet import Fernet >>> >>> # Encrypt >>> key = Fernet.generate_key() # Need a key first >>> print(type(key)) # bytes <class 'bytes'> >>> print(key) # DO NOT SHARE THIS NORMALLY b'8umW9Eygk1eZDN-e0YBkgPhdBr6Lwz-GsJRRdfgiR-c=' >>> my_fernet = Fernet(key) >>> encrypted_bytes = my_fernet.encrypt(b"Hello, world!") >>> print(encrypted_bytes) b'gAAAAABeQi2FRND9e7hgs5XdY2cvxItJXqRST37g7UaZRDoRQiuOxTFdSfnsv8D22RzvUCEAKDM6A84u4p_E3WKeIBsL24Ztnw==' >>> >>> # Decrypt >>> clear_text = my_fernet.decrypt(encrypted_bytes) >>> print(clear_text) b'Hello, world!' >>>
After following this guide you should know how to symmetrically encrypt data in Python using the Fernet (AES) encryption.