我正在try 将原始字符串密码转换为Fernet密钥.此代码不起作用:

# 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()

现在,您可以使用您的_class_instance.fern进行加密/解密

以下是加密/解密数据的方法:

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

Python相关问答推荐

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

删除所有列值,但判断是否存在任何二元组

如何让Flask 中的请求标签发挥作用

如何在polars(pythonapi)中解构嵌套 struct ?

如何在python xsModel库中定义一个可选[December]字段,以产生受约束的SON模式

将pandas Dataframe转换为3D numpy矩阵

将9个3x3矩阵按特定顺序排列成9x9矩阵

如何使用Python以编程方式判断和检索Angular网站的动态内容?

如何设置视频语言时上传到YouTube与Python API客户端

计算分布的标准差

索引到 torch 张量,沿轴具有可变长度索引

什么是合并两个embrame的最佳方法,其中一个有日期范围,另一个有日期没有任何共享列?

判断solve_ivp中的事件

为什么if2/if3会提供两种不同的输出?

Gekko中基于时间的间隔约束

Pandas—MultiIndex Resample—我不想丢失其他索引的信息´

解决Geopandas和Altair中的正图和投影问题

以极轴表示的行数表达式?

为什么我的scipy.optimize.minimize(method=";newton-cg";)函数停留在局部最大值上?

如何在Python中画一个只能在对角线内裁剪的圆?