from cryptography.fernet import Fernet
import base64
# Put this somewhere safe!
key = Fernet.generate_key()
f = Fernet()
token = f.encrypt(b"A really secret message. Not for prying eyes.")
token
print f.decrypt(token)
How can I generate my own key instead of fernet.genrate_key()
?
In fernet a key can be generated using one of fernet's Key Derivation Functions
One of the functions provided by fernet is the 'Password Based Key Derivation Function 2'. An example that uses PBKDF2HMAC can be found at Using Passwords with Fernet. This is discussed in git issue #1333 of pyca/cryptography, maebert points out that the example uses salt=os.urandom(16) and will generate a new key from a password each time the kdf class is constructed with a different salt value.
If you need to use a custom key derivation function look at source code for kdf and pbkdf2 to have an example of a class that implements the KeyDerivationFunction interface.
A class that matches its signature and implements the interface should be able to be dropped in as a custom key derivation function.