您的字符串长度应为32个字节.
要确保此大小,您可以对其进行散列,然后将其传递给您的函数,如下所示:
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()
现在,您可以使用您的_class_instance.fern进行加密/解密
以下是加密/解密数据的方法:
encrypted = your_class_instance.fern.encrypt(b"my secret data123")
decrypted = your_class_instance.fern.decrypt(encrypted)