1

I want to convert a string to use it as a custom key for Fernet.

Current code

masterKey = base64.b64encode("F4D27D47".encode("utf-8"))
crypter = Fernet(masterKey)

However this raises and exception:

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

Thanks in advance.

  • 4
    The error message describes the problem exactly. Your key is neither 32 bytes (but only 8) nor is it Base64**url** encoded (but Base64). You can generate a 32 bytes Base64url encoded key e.g. with `key = Fernet.generate_key()`, see [here](https://cryptography.io/en/latest/fernet/#fernet-symmetric-encryption). If you want to use a string/password, you can derive a 32 bytes key with a key derivation function (like PBKDF2), e.g. [here](https://asecuritysite.com/encryption/fernet2). – Topaco Jun 26 '21 at 09:59

1 Answers1

1

The following code should work fine:

code_bytes = code.encode("utf-8")
key = base64.urlsafe_b64encode(code_bytes.ljust(32)[:32])
fernet = Fernet(key)

ljust(32) pads the password bytes with null bytes to ensure the key is 32 bytes long. Then [:32] truncates the key to 32 bytes if it's longer than that. Finally, the key is encoded using base64.urlsafe_b64encode() to obtain a URL-safe base64-encoded key.

Lars K.
  • 59
  • 4