IV必须为16字节长的AES加密错误

use*_*493 4 python encryption pycrypto

我正在使用pycrypto模块进行AES加密。使用文档,我记下了以下函数,但是它IV must be 16 bytes long总是会出错,但是我使用的是16字节长的IV。

def aes_encrypt(plaintext):
    """
    """
    key = **my key comes here**
    iv = binascii.hexlify(os.urandom(16)) # even used without binascii.hexlify)

    aes_mode = AES.MODE_CBC

    obj = AES.new(key, aes_mode, iv)

    ciphertext = obj.encrypt(plaintext)
    return ciphertext
Run Code Online (Sandbox Code Playgroud)

Ebr*_*Him 6

用这个:

from Crypto.Cipher import AES 
import binascii,os

def aes_encrypt(plaintext):
    key = "00112233445566778899aabbccddeeff"
    iv = os.urandom(16)
    aes_mode = AES.MODE_CBC
    obj = AES.new(key, aes_mode, iv)
    ciphertext = obj.encrypt(plaintext)
    return ciphertext
Run Code Online (Sandbox Code Playgroud)

工作方式如下:

>>> aes_encrypt("TestTestTestTest")
'r_\x18\xaa\xac\x9c\xdb\x18n\xc1\xa4\x98\xa6sm\xd3'
>>> 
Run Code Online (Sandbox Code Playgroud)

区别在于:

>>> iv =  binascii.hexlify(os.urandom(16))
>>> iv
'9eae3db51f96e53f94dff9c699e9e849'
>>> len(iv)
32
>>> iv = os.urandom(16)
>>> iv
'\x16fdw\x9c\xe54]\xc2\x12!\x95\xd7zF\t'
>>> len(iv)
16
>>>
Run Code Online (Sandbox Code Playgroud)