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()
?
If you need to generate a new fernet key you can use the following code snippet. from cryptography. fernet import Fernet fernet_key = Fernet. generate_key() print(fernet_key.
Fernet makes it easy for Python developers to implement encryption and authentication into their applications. Fernet is a useful tool in the arsenal of a Python developer. It aims to help them secure data without running into all of the risks that come with implementing cryptographic primitives yourself.
The key can not be memorized and people would typically store it somewhere in a file and use copy-paste to enter it. This increases the risk that the key will leak. As an alternative, a so-called key-derivation mechanism can be used. In that case, the key bytes are not generated randomly with the Fernet.
The implementation shows how this is done:
return base64.urlsafe_b64encode(os.urandom(32))
So to generate your own you'll want to generate 32 cryptographically secure random bytes and then urlsafe
base64 encode them. Of course, since generate_key
already does this you should probably just call that unless you need to generate the key outside of your Python process.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With