【问题标题】:PyCryptoDome/cryptography inequality with AES-CFB in pythonPyCryptoDome/密码不等式与python中的AES-CFB
【发布时间】:2020-04-29 22:46:16
【问题描述】:

在运行测试以确保两个不同的库提供相同的输出时,我发现CFB 并没有。复制问题的代码是:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from Crypto.Cipher import AES

KEY = b'legoroojlegorooj'
IV = b'legoroojlegorooj'

aes = Cipher(algorithms.AES(KEY), modes.CFB(IV), default_backend()).encryptor()
output_data = aes.update(b'Feathers fall as fast as bowling balls.') + aes.finalize()
del aes


ctr = AES.new(KEY, AES.MODE_CFB, iv=IV)
output_data2 = ctr.encrypt(b'Feathers fall as fast as bowling balls.')

assert output_data == output_data2  # AssertionError

如有任何帮助解决这个问题,我们将不胜感激。

此代码适用于 modes.OFB(IV)AES.MODE_OFB

【问题讨论】:

  • 你是什么意思“不要使用某些模式” - 你能发布你得到的错误(见How to Ask
  • @ErtySeidohl 抱歉,这是我最初的草稿 - 没必要,我会删除它。

标签: python encryption aes pycryptodome python-cryptography


【解决方案1】:

CFB mode 中必须指定移位寄存器的大小,因此不同的库通常使用不同的默认值。为了区分,移位寄存器的位大小通常附加到 CFB 后,即 CFB8 使用 8 位移位寄存器,CFB128 使用 128 位移位寄存器。

Cryptography 有两种变体 CFB8 和 CFB128,后者简称为 CFB。 PyCryptodome 允许使用参数segment_size 设置为8 位的整数倍,默认值为8 位。

所以在当前代码中 Cryptography 使用 CFB128 而 PyCryptodome 使用 CFB8(其默认值),这会导致不同的结果。

以下组合有效:

  • PyCryptodomesegment_size=128Cryptography 与 CFB。都对应CFB128:

    # CFB with a 128 bit shift-register
    # Output as hex-string: 63230751cc1efe25b980d9e707396a1a171cd413e6e77f1cd7a2d3deb2217255a36ae9cbf86c66
    ...
    aes = Cipher(algorithms.AES(KEY), modes.CFB(IV), default_backend()).encryptor()
    ...
    ctr = AES.new(KEY, AES.MODE_CFB, iv=IV, segment_size=128)
    ...
    
  • PyCryptodomesegment_size=8(默认值)和 Cryptography 与 CFB8。都对应CFB8:

    # CFB with a 8 bit shift-register
    # Output as hex-string: 63d263889ffe94dd4740580067ee798da474c567b8b54319a5022650085c62674628f7c9e790c3
    ...
    aes = Cipher(algorithms.AES(KEY), modes.CFB8(IV), default_backend()).encryptor()
    ...
    ctr = AES.new(KEY, AES.MODE_CFB, iv=IV, segment_size=8)
    ...
    

请注意,(1) 两个 Python 库都为 OFB mode 提供了相同的结果,因为它们都使用 OFB128。 (2) CFB128 比 CFB8 快:在 CFB8 中,AES 加密必须为每个块调用 16 次,而在 CFB128 中为 1 次。

【讨论】:

  • 谢谢你 - 我认为有人需要改进 pycryptodome 的文档。它们可能更清晰几个数量级。
猜你喜欢
  • 2017-04-12
  • 2020-11-09
  • 2019-03-11
  • 2018-09-20
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多