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

Python实现DES加解密报错:utf-8解码失败问题排查

DES加密解密报错原因及修复方案

问题根源

你遇到的'utf-8' codec can't decode byte 0xc1...错误,本质是EAX模式的使用方式错误:

  • EAX属于AEAD(认证加密带关联数据)模式,加密时会自动生成唯一的nonce(随机数),这个值是解密的核心依赖,必须和密文一起传递。
  • 你当前的代码中,加密和解密分别创建独立的DES实例,两边的nonce不匹配,导致解密出无意义的乱码,自然无法通过UTF-8解码。

修复后的代码

from Crypto.Cipher import DES

key = 'abcdefgh'

def encrypt(msg):
    cipher = DES.new(key.encode('utf-8'), DES.MODE_EAX)
    ciphertext, tag = cipher.encrypt_and_digest(msg.encode('utf-8'))
    # 返回nonce、tag和密文,tag用于验证数据完整性
    return cipher.nonce, tag, ciphertext

def decrypt(nonce, tag, ciphertext):
    cipher = DES.new(key.encode('utf-8'), DES.MODE_EAX, nonce=nonce)
    plaintext = cipher.decrypt_and_verify(ciphertext, tag)
    return plaintext.decode('utf-8')

# 加密流程
nonce, tag, ciphertext = encrypt('Python')
# 解密流程
plaintext = decrypt(nonce, tag, ciphertext)

print(f'Cipher text: {ciphertext}')
print(f'Plain text: {plaintext}')

关键说明

  • 用encrypt_and_digest()替代encrypt(),同时获取密文和用于完整性验证的tag,防止数据被篡改。
  • 加密时返回nonce、tag、ciphertext三个值,解密时必须传入相同的nonce和tag才能正确解密。
  • 解密用decrypt_and_verify()替代decrypt(),既完成解密又验证数据完整性,安全性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:01:02