python - AES CTR解密: Cryptography and Cryptodome gi

下面的代码片段使用 Cryptodome 对一些字节进行 AES 解密,正如我预期的那样:

from Crypto.Cipher import AES
from Crypto.Util import Counter

key = b'\x12' * 32
decryptor = AES.new(key, AES.MODE_CTR,counter=Counter.new(nbits=128, little_endian=True))
print(decryptor.decrypt(b'Something encrypted'))

下面使用 Python 密码学,并给出不同的结果:

from cryptography.hazmat.primitives.ciphers import Cipher, modes, algorithms

key = b'\x12' * 32
decryptor = Cipher(algorithms.AES(key), modes.CTR(b'\0' * 16)).decryptor()
print(decryptor.update(b'Something encrypted'))

为什么?以及如何更改 Python 加密版本以输出与 Cryptodome 相同的结果?

(上下文正在编写用于解压缩文件的AES解密代码,并正在考虑使用Python Cryptography)

最佳答案

在 PyCryptodome 中,计数器默认从 1 开始。此外,小端计数的计数器如下所示:0x0100...0000、0x0200...0000、0x0300...0000

由于在密码学中无法配置计数器的字节顺序并且使用大端,因此无法实现此计数。虽然可以将起始值显式设置为 0x0100...00 ,但计数器随后会计数:0x0100...0000, 0x0100...0001, 0x0100...0002

这可以用下面的代码来验证:

from Crypto.Cipher import AES
from Crypto.Util import Counter
key = b'\x12' * 32
decryptor = AES.new(key, AES.MODE_CTR,counter=Counter.new(nbits=128, little_endian=True, initial_value=1))
print(decryptor.decrypt(b'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx').hex())

from cryptography.hazmat.primitives.ciphers import Cipher, modes, algorithms
key = b'\x12' * 32
decryptor = Cipher(algorithms.AES(key), modes.CTR(b'\x01' + b'\0' * 15)).decryptor()
print(decryptor.update(b'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx').hex())

输出:

faebe2ab213094fcd5c9ec3dae32372b 13b3b971b7694faa5e15f5387ac5a67f bc5dbc82ce54cf1bbe2719488b322078
faebe2ab213094fcd5c9ec3dae32372b 6ddda72218780c287bc74956395bf7db 0603820b26889ec64e7f7964a14518c5

因为第一个 block 的计数器值匹配,所以第一个 block 是相同的。但是,由于以下 block 的不同值,以下 block 是不同的。

当 PyCryptodome 被配置为 little endian 时,我目前看不出如何使用 Cryptography 库来生成 PyCryptodome 库结果。

关于python - AES CTR解密: Cryptography and Cryptodome give different results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69144760/

相关文章:

c# - 如何在 C# 中使用预处理器指令仅在 Windows 10 上执行一些代码?

c++ - 在 constexpr 分支中使用枚举类值

laravel - Laravel 中的 getClientOriginalExtension()

python - Azure Databricks python 命令显示当前集群配置

c - 有没有办法从未知字节设置/清除位,同时保持所有其他位不变?

docker - 使用 deps.edn 在容器中安装依赖项

c - 栈在使用Pthread的多线程程序中是如何工作的?

c++ - 在 "Effective Modern C++"示例中在索引运算符之前使用 std::f

c# - Parallel.Foreach 和每个产生不同的结果 : Why is my code

flutter - 如何在 flutter 中的行之间写 OR