Search code examples
pythoncryptographybytevalueerrorfernet

How can I generate my own Fernet key in Python?


I've tried something like this but it doesn't seem to be working:

from cryptography.fernet import Fernet
from base64 import urlsafe_b64encode as b64e
    bytes_gen = b64e(PASSWORD.encode())
    if len(bytes_gen) < 32:
        bytes_gen += b'=' * (32 - len(bytes_gen))
    elif len(bytes_gen) > 32:
        bytes_gen = bytes_gen[:32]
    print(bytes_gen, len(bytes_gen))
    f = Fernet(bytes_gen)

Terminal:

ValueError: Fernet key must be 32 url-safe base64-encoded bytes.

Solution

  • You are reading it wrong. The key is a cryptographic keys, which are usually 16, 24 or 32 bytes in size. So the phrase "Fernet key must be 32 url-safe base64-encoded bytes." doesn't mean that the encoding needs to be 32 characters in size, it means that there are 32 bytes that need to be encoded.

    You seem to want to use a password instead of a key though. In that case you need to read the appropriate section in the manual that explains how PBKDF2 can be used to derive a key from a password.