IV must be 16 bytes long error in AES encryption

半世苍凉 提交于 2020-04-29 14:34:27

问题


I am using pycrypto module for AES encryption. And using documentation I have write down the below function but it al;ways gives error IV must be 16 bytes long but I am using 16 byte long 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

回答1:


Use this:

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

Works as below:

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

That's the difference:

>>> 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
>>>


来源:https://stackoverflow.com/questions/36834580/iv-must-be-16-bytes-long-error-in-aes-encryption

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!