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
相关产品推荐
相关产品推荐

