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

PyCrypto AES解密失败 疑似字节与字符串转换相关问题

Flask PyCrypto AES解密乱码问题排查

核心问题点

  • 入参未解码:加密逻辑中你对原始密文做了b16encode转字符串处理,解密时拿到的cipher是base16编码后的字符串,不能直接传入解密方法,需要先还原为原始密文字节
  • 密钥未解码:keygen返回的是原始密钥经b16encode后的字符串,解密时传入的key是该字符串,需要先解码得到原始16字节密钥才能用于初始化AES实例
  • IV不一致/缺失:CFB模式要求加密和解密使用完全相同的IV向量,你当前代码中未实现IV的生成、传递逻辑,若加密和解密的IV不匹配必然导致解密失败
  • 解密后处理错误:解密得到的plaintext本身就是原始明文字节,不需要再做b16encode,直接按utf-8解码即可得到可读明文

修正后代码示例

from Crypto.Cipher import AES
from os import urandom
from base64 import b16encode, b16decode

def keygen(self):
    key = urandom(16)
    dkey = b16encode(key).decode('utf-8')
    return {'key': dkey}

def encrypt(self, key, raw):
    # 解码得到原始16字节密钥
    raw_key = b16decode(key.encode('utf-8'))
    # 每次加密生成独立IV,解密时需要和密文配套使用
    iv = urandom(16)
    crypt = AES.new(raw_key, AES.MODE_CFB, iv)
    ciphertext = crypt.encrypt(raw.encode('utf-8'))
    # 密文、IV都做base16编码后返回
    ciph = b16encode(ciphertext).decode('utf-8')
    iv_str = b16encode(iv).decode('utf-8')
    return {'secret': ciph, 'iv': iv_str}

def decrypt(self, key, cipher, iv):
    # 分别解码密钥、IV、密文为原始字节
    raw_key = b16decode(key.encode('utf-8'))
    raw_iv = b16decode(iv.encode('utf-8'))
    raw_cipher = b16decode(cipher.encode('utf-8'))
    crypt = AES.new(raw_key, AES.MODE_CFB, raw_iv)
    plaintext = crypt.decrypt(raw_cipher)
    # 直接解码明文为可读字符串
    raw = plaintext.decode('utf-8')
    return {'message': raw}

适配调整

你需要在请求参数中新增iv字段,调用解密接口时传入加密接口返回的iv值即可正常解密。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:36:04