Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"ValueError: Fernet key must be 32 url-safe base64-encoded bytes." When converting str to fernet key

I’m trying to convert a raw string password into a fernet key. This code doesn’t work:

# Convert the string to bytes
key_bytes = self.PrintPassword.encode()

# Base64 encode the bytes
base64_encoded_key = base64.urlsafe_b64encode(key_bytes)

# Create a Fernet key using the encoded bytes
fernet_key = base64.urlsafe_b64decode(base64_encoded_key)

self. Fern = Fernet(fernet_key)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your string should be 32 bytes long.
to ensure this size, you can hash it and then pass it to your function like this:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.fernet import Fernet
import os
import base64

class YourClass:
    def __init__(self, password):
        self.password = password

    def generate_fernet_key(self):
        # Convert the password to bytes if it's not already
        password_bytes = self.password.encode()

        # Generate a salt
        salt = os.urandom(16)

        # Use PBKDF2HMAC to derive a secure key from the password
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,  # Fernet keys are 32 bytes
            salt=salt,
            iterations=100000,
            backend=default_backend()
        )
        key = base64.urlsafe_b64encode(kdf.derive(password_bytes))
        self.fern = Fernet(key)

        # Optionally, return the key and salt for storage
        return key, salt

# Example usage
your_class_instance = YourClass("your_password_here")
fernet_key, salt = your_class_instance.generate_fernet_key()

Now you can use your_class_instance.fern for encryption/decryption

This is how you can encrypt/decrypt data:

encrypted = your_class_instance.fern.encrypt(b"my secret data123")
decrypted = your_class_instance.fern.decrypt(encrypted)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading