[Cryptography-dev] Fernet newbie question: suppling existing key for decoding

Paul Kehrer paul.l.kehrer at gmail.com
Mon Jan 5 19:26:20 CET 2015


Thanks for the update David.

I'd strongly recommend against using that construction as it is just doing a single SHA256 hash of your password and then base64 encoding it. While a password is definitely lower entropy than 32 bytes of random you can still derive a key suitable for encryption from a password by using a KDF (key derivation function). KDFs are useful in this context because they raise the cost of computing the key so that an attacker can't easily brute force the password. Consider replacing the get_key function with something using PBKDF2HMAC (https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions/#cryptography.hazmat.primitives.kdf.pbkdf2.PBKDF2HMAC). An even better KDF would be something like scrypt, but unfortunately we don't support that in pyca/cryptography yet.

This definitely is showing a need for an official password-based encryption key derivation for Fernet...

-Paul Kehrer
On January 5, 2015 at 12:07:31 PM, David Evans (djve60 at gmail.com) wrote:

I found the answer to what I was trying to find at ​http://incolumitas.com/2014/10/19/using-the-python-cryptography-module-with-custom-passwords/ when following up on the URLs.

In case the site goes off line the code I was after is just (copied from the site) by Nikolai Tschacher:
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend

def get_key(password):
    digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
    digest.update(password)
    return base64.urlsafe_b64encode(digest.finalize())

def encrypt(password, token):
    f = Fernet(get_key(key))
    return f.encrypt(bytes(token))

def decrypt(password, token):
    f = Fernet(get_key(password))
    return f.decrypt(bytes(token))

but the problem I have with this is using a non-randomized password helps subvert the security of the 32-bit random password that Fernet provides. However, as Nikolai notes, it's more usable for interactive activities.

For new code I'll be using Fernet but for existing code I think I'm forced to keep to PyCrypto. Since a Fernet message is a self-signed (a little like a PKCS12 type file) it will not be appropriate for many existing processes but I think it should be used where possible. 

Thanks for the help,

David
_______________________________________________  
Cryptography-dev mailing list  
Cryptography-dev at python.org  
https://mail.python.org/mailman/listinfo/cryptography-dev  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cryptography-dev/attachments/20150105/f7aaf9c1/attachment.html>


More information about the Cryptography-dev mailing list