【问题标题】:Python AES implementations differencePython AES 实现的区别
【发布时间】:2014-05-14 11:11:42
【问题描述】:

我正在比较来自 pycryptocryptography.io 库的 Python 中的 AES 实现。

from cryptography.hazmat.primitives.ciphers import Cipher, modes, algorithms
from cryptography.hazmat.backends import default_backend  # http://cryptography.io
from Crypto.Cipher import AES  # http://pycrypto.org

key = b'Sixteen byte key'
iv = b'Sixteen byte ivv'
cipher1 = AES.new(key, AES.MODE_CFB, iv)
cipher2 = Cipher(algorithms.AES(key), modes.CFB(iv), default_backend())

plaintext = b"Plaintext"

print(cipher1.encrypt(plaintext))
print(cipher1.decrypt(plaintext))
print(cipher2.encryptor().update(plaintext))
print(cipher2.decryptor().update(plaintext))

MWE 打印:

b'\xe4\xb4\xeb\xe3Si\x9ap\xee'
b'7\xda\x98\xee\x05\xe4\xa0\xc7,'
b'\xe4"\xd4mo\xa3;\xa9\xe0'
b'\xe4"\xd4mo\xa3;\xa9\xe0'

为什么输出不同?

【问题讨论】:

    标签: python encryption cryptography encryption-symmetric pycrypto


    【解决方案1】:

    答案似乎是 PyCrypto 默认实现 CFB-8,它是普通 CFB 的变体。 https://github.com/digitalbazaar/forge/issues/100 更详细地描述了这个问题。

    【讨论】:

    • 也许你的意思是CFB-8? CFB PyCrypto 的默认行为描述为 here: segment_size (integer) - (Only MODE_CFB).The number of bits the plaintext and ciphertext are segmented in. It must be a multiple of 8. If 0 or not specified, it will be assumed to be 8.
    • @SquareRootOfTwentyThree 确实,已修复。
    【解决方案2】:

    根据 Alex Gaynor 的回答,这里有更详细的描述:

    根据标准,输入大小必须是段大小的倍数。大多数实现默认使用 16 字节(128 位)段大小,并忽略此要求。 PyCrypto 默认使用 8 字节段,但你可以像这样更改它:

    cipher1 = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
    

    这会产生与其他库相同的加密数据。

    【讨论】:

      【解决方案3】:

      请使用加密模式为“CFB8”。 pycrypto 和密码学输出将匹配。 对于 ex.cipher2 = Cipher(algorithms.AES(key),modes.CFB8(iv),default_backend())

      【讨论】:

      • 在我的项目中,我们之前使用的是 pycrypto aes 实现。
      • 在我的项目中,我们使用默认段大小为 8 而不是 128 的 pycrypto aes 实现。当我们想用加密实现替换它时,我们使用了 modes.CFB8 模式来匹配加密输出和 pycrypto 输出。如果你使用 mode.CFB 那么加密输出不匹配
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      相关资源
      最近更新 更多