前缀IV值AES加密会产生错误

时间:2018-11-30 11:00:30

标签: python encryption aes

当我尝试使用带前缀的IV值时,我得到了Error 131073 while instatiating the CFB mode。当我将其更改为随机时,它可以工作,但是我需要给它加上前缀。

我尝试过的操作会出现此错误:

import base64
from Crypto.Cipher import AES
import hashlib
from Crypto import Random
import binascii

def pad(s):
    return s + b"\0" * (AES.block_size - len(s) % AES.block_size)

def encrypt(message, key, key_size=256):
    message = pad(message)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(key, AES.MODE_CFB, iv)
    return base64.b64encode(cipher.encrypt(message))

key = hashlib.sha256(b'P9KcPLf+q21f9DUnI0cyP1xgALRa8+uKfZXiNIcjphM=').digest()
key1 = base64.b64encode(key)
iv_value = b'lEvSlTN0Q7gu9sAUvPTySQ=='
iv = base64.b64encode(iv_value) #How can prefix this?

cipher = AES.new(key, AES.MODE_CFB, iv)

message = Mac_AddressBytes + ip_address_Bytes + DeviceIdBytes
msg = iv + cipher.encrypt(message)

s = encrypt(message, key)

DeviceIdentity = "0x" + s.decode('utf-8')
print(str(DeviceIdentity))

但是当我将IV设置为随机值时,我将获得所需的输出。

iv = Random.new().read(AES.block_size)

如何为IV使用前缀值?

注意:Mac_AddressBytesip_address_BytesDeviceIdBytes是MAC地址,Ip地址和DeviceID的有效值,这些值是随机生成的字符串

1 个答案:

答案 0 :(得分:2)

您得到的错误是

ValueError: Incorrect IV length (it must be 16 bytes long)

您必须解码iv

iv = base64.b64decode(iv_value)