Python 中的 AES 128
AES 128 in Python
我不知道为什么当我使用 PyCrypto (Crypto.Cipher- AES) 在 AES 中加密文本时,结果与 C 中的代码生成的密文不同。
例如,下面的代码给了我
99756ed0115f676cef45ae25937bfd63247358a80803dde3fc1eae4953ee7277
而不是
CC613A0BDC930DABEA7A26126CE489EA
这是我的代码:
key = '1F61ECB5ED5D6BAF8D7A7068B28DCC8E'
IV = 16 * '\x00'
mode = AES.MODE_CBC
encryptor = AES.new(key, mode, IV=IV)
text = '020ABC00ABCDEFf8d500000123456789'
ciphertext = encryptor.encrypt(text)
print binascii.hexlify(ciphertext)
您需要 unhexlify
键和文本(IPython 中的示例使用 Python 3);
In [1]: from Crypto.Cipher import AES
In [2]: import binascii
In [3]: import os
In [4]: key = binascii.unhexlify('1F61ECB5ED5D6BAF8D7A7068B28DCC8E')
In [5]: IV = os.urandom(16)
In [6]: binascii.hexlify(IV).upper()
Out[6]: b'3C118E12E1677B8F21D4922BE4B2398E'
In [7]: encryptor = AES.new(key, AES.MODE_CBC, IV=IV)
In [8]: text = binascii.unhexlify('020ABC00ABCDEFf8d500000123456789')
In [9]: ciphertext = encryptor.encrypt(text)
In [10]: print(binascii.hexlify(ciphertext).upper())
b'2133D236609558353F7C501E6EBBB8D9
编辑: 正如 André Caron 在评论中正确指出的那样,使用仅由零组成的 IV 通常是 bad idea。我已将代码更改为使用随机 IV。请注意,IV 也应传达给接收者;解密需要它。通常 IV 被添加到密文之前。
我不知道为什么当我使用 PyCrypto (Crypto.Cipher- AES) 在 AES 中加密文本时,结果与 C 中的代码生成的密文不同。
例如,下面的代码给了我
99756ed0115f676cef45ae25937bfd63247358a80803dde3fc1eae4953ee7277
而不是
CC613A0BDC930DABEA7A26126CE489EA
这是我的代码:
key = '1F61ECB5ED5D6BAF8D7A7068B28DCC8E'
IV = 16 * '\x00'
mode = AES.MODE_CBC
encryptor = AES.new(key, mode, IV=IV)
text = '020ABC00ABCDEFf8d500000123456789'
ciphertext = encryptor.encrypt(text)
print binascii.hexlify(ciphertext)
您需要 unhexlify
键和文本(IPython 中的示例使用 Python 3);
In [1]: from Crypto.Cipher import AES
In [2]: import binascii
In [3]: import os
In [4]: key = binascii.unhexlify('1F61ECB5ED5D6BAF8D7A7068B28DCC8E')
In [5]: IV = os.urandom(16)
In [6]: binascii.hexlify(IV).upper()
Out[6]: b'3C118E12E1677B8F21D4922BE4B2398E'
In [7]: encryptor = AES.new(key, AES.MODE_CBC, IV=IV)
In [8]: text = binascii.unhexlify('020ABC00ABCDEFf8d500000123456789')
In [9]: ciphertext = encryptor.encrypt(text)
In [10]: print(binascii.hexlify(ciphertext).upper())
b'2133D236609558353F7C501E6EBBB8D9
编辑: 正如 André Caron 在评论中正确指出的那样,使用仅由零组成的 IV 通常是 bad idea。我已将代码更改为使用随机 IV。请注意,IV 也应传达给接收者;解密需要它。通常 IV 被添加到密文之前。