问题出现在Cryptography和Cryptodome库实现AES CTR模式解密时使用不同的初始化向量。解决方法是确保在使用两个库时,初始化向量相同。
示例代码:
from Crypto.Cipher import AES
from Crypto.Util import Counter
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
# 设置相同的输入参数
key = b'0123456789abcdef'
nonce = b'0000000000000001'
data = b'Hello, world!'
# 使用Cryptodome库进行AES CTR解密
ctr = Counter.new(128, initial_value=int.from_bytes(nonce, byteorder='big'))
cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
ciphertext = cipher.encrypt(data)
# 使用Cryptography库进行AES CTR解密
backend = default_backend()
counter = modes.Counter(nonce)
cipher = Cipher(algorithms.AES(key), modes.CTR(counter),
backend=backend)
decryptor = cipher.decryptor()
ciphertext2 = decryptor.update(ciphertext) + decryptor.finalize()
# 通过比较两个结果来判断是否相同
print(ciphertext == ciphertext2) # 输出True