Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating own key with Python Fernet

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()?

like image 406
Anonymous Avatar asked Jun 08 '17 10:06

Anonymous


People also ask

How do you generate a key using Fernet in Python?

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.

What is Fernet key in Python?

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.

How do I store my Fernet key?

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.


2 Answers

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.

like image 150
Paul Kehrer Avatar answered Sep 19 '22 09:09

Paul Kehrer


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.

like image 37
James Avatar answered Sep 20 '22 09:09

James