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

AES-CTR语法问题求助:多次加解密结果不一致

问题根源

你的代码核心问题在于复用了同一个AES-CTR模式的cipher实例。CTR是流加密模式,cipher实例内部维护着一个计数器,每次调用encrypt后计数器会自动递增,记录当前密钥流的位置。第二次加密时,计数器从上次结束的位置继续生成密钥流,但解密时你每次都用初始nonce创建新的解密器,计数器从头开始,导致密钥流不匹配,解密出的明文自然错误。

修复方案

正确的做法是每次加密都生成新的nonce和cipher实例,并将nonce与密文绑定存储/传输(因为解密必须使用加密时的同一个nonce)。修改后的代码如下:

from cryptography.hazmat.primitives.ciphers import AES
import base64
import os

class AESCipher:
    def __init__(self):
        self.key = os.urandom(16)  # 生成16字节随机密钥(AES-128)

    def encrypt(self, data):
        # 每次加密生成新的16字节nonce
        nonce = os.urandom(16)
        # 创建新的CTR模式cipher实例
        cipher = AES.new(self.key, AES.MODE_CTR, nonce=nonce)
        cipher_text = cipher.encrypt(data.encode('utf-8'))
        # 将nonce与密文拼接后Base64编码,方便统一传输
        combined_data = nonce + cipher_text
        return base64.b64encode(combined_data)

    def decrypt(self, encrypted_data):
        # 解码Base64并拆分nonce和密文
        combined_data = base64.b64decode(encrypted_data)
        nonce = combined_data[:16]
        cipher_text = combined_data[16:]
        # 使用对应nonce创建解密器
        decrypt_cipher = AES.new(self.key, AES.MODE_CTR, nonce=nonce)
        plain_text = decrypt_cipher.decrypt(cipher_text)
        return plain_text.decode('utf-8')
关键说明
  1. 每次加密生成新nonce:CTR模式要求同一个密钥下nonce必须唯一,否则会导致密钥流重复,彻底破坏加密安全性。
  2. 绑定nonce与密文:解密必须依赖加密时的nonce,因此需要将二者一起存储或传输,这里采用前16字节为nonce、后续为密文的拼接方式。
  3. 避免复用cipher实例:CTR模式的cipher是有状态的,复用会导致计数器偏移,引发加解密不匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:27:56