所以我试图将原始字符串密码转换为 fernet 密钥,我已经解决了无数的问题,甚至使用 ChatGPT 因为如果有人理解我为什么做错了并且可以提供一点帮助,我非常绝望请这样做。
# 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)
您的字符串长度应为 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()
现在您可以使用 your_class_instance.fern 进行加密/解密