This article is part of a series on the Python cryptography library.
The cryptography module can be installed using pip, like this:
pip install cryptography
If you use Anaconda, you can also install cryptography in the usual way with conda.
Both pip and conda download a pre-built executable from a repository. There is, at least theoretically, a possibility of an attacker hacking the repository and replacing the original executable with their own doctored version, that might contain back doors.
If your application requires a high degree of security, you should consider building the library yourself. Instructions for doing this are included on the official cryptography module website at cryptography.io.
You can check that the module is installed correctly using this simple program that creates a key then encodes and decodes a message:
from cryptography.fernet import Fernet # Generate a key key = Fernet.generate_key() # Create a Fernet instance with the key cipher = Fernet(key) # Encrypt a message message = "Message to be encrypted".encode('utf-8') token = cipher.encrypt(message) print(token.hex()) # Decrypt the cipertext decoded = cipher.decrypt(token) print(decoded)
print(token.hex()) should print the encrypted message, something like:
674141414141426555704e5a6e423947 333562524c504b333751745a47576432 3266305a6a33356c3645304838425446 316e5a58627850634741425f30545576 6b637956526e30664d75523337325261 776a543375785a677a64434353527142 61516e7446766f326f6d4a6c4d313363 84449776f4a673d
The encrypted data will be different every time, because it contains random elements.
print(decoded) prints the result of decrypting the
token. It should be:
b'Message to be encrypted'
We will look at this code in more detail in the Fernet encryption section.
Copyright (c) Axlesoft Ltd 2020