You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报错:'bytes'对象无'decrypt'属性,加密示例调试求助

问题解决方案

错误根源分析

触发AttributeError: 'bytes' object has no attribute 'decrypt'的核心原因有两个:

  1. 加密对象错误:你用公钥加密的是用户输入的plain_data,而非Fernet生成的AES对称密钥key,导致解密后得到的dec_key根本不是可用的加密密钥,只是原明文的bytes。
  2. 调用方式错误:即便拿到正确的AES密钥,它本身是bytes类型,没有decrypt方法——必须用这个密钥实例化Fernet对象,才能调用解密接口。

修正步骤

1. 修正对称密钥的加密逻辑

把公钥加密的对象从plain_data改为Fernet生成的key:

# 原错误代码
enc_key = public_key.encrypt(plain_data, padding.OAEP(...))

# 修正后
enc_key = public_key.encrypt(key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))

2. 用解密后的密钥创建Fernet对象

删除无用的dec_key.decode('utf-8'),替换为实例化Fernet对象再执行解密:

# 原错误代码
dec_key.decode('utf-8')
dec_msg = dec_key.decrypt(enc_msg)

# 修正后
dec_f_object = Fernet(dec_key)
dec_msg = dec_f_object.decrypt(enc_msg)

完整修正代码

from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa,padding
from cryptography.hazmat.primitives import serialization,hashes

key = Fernet.generate_key()
f_object = Fernet(key)

# 用AES加密明文
plain_data = bytes(input(), encoding='utf8')
enc_msg = f_object.encrypt(plain_data)

# 加载公钥/私钥
with open("public_key.pem", "rb") as key_file:
     public_key = serialization.load_pem_public_key(key_file.read(),backend=default_backend())
with open("private_key.pem", "rb") as key_file:
     private_key = serialization.load_pem_private_key(key_file.read(),password=None,backend=default_backend())

# 加密对称密钥,再解密得到原始对称密钥
enc_key = public_key.encrypt(key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
print("enc_key and enc_message send through insecure channel.")
dec_key = private_key.decrypt(enc_key,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))

# 用解密后的对称密钥解密AES加密消息
dec_f_object = Fernet(dec_key)
dec_msg = dec_f_object.decrypt(enc_msg)

# 输出解密结果(转成字符串更易读)
print(dec_msg.decode('utf-8'))

额外说明

  • Fernet的密钥本身是URL-safe的base64编码bytes,无需解码为字符串,直接传入Fernet构造函数即可。
  • 最后用decode('utf-8')把解密后的bytes转回字符串,是为了让输出更直观,可根据需求调整。

内容的提问来源于stack exchange,提问作者Dino_coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 22:35:03