Search code examples
pythonencryptionaes

Prefixed IV values AES Encryption yields an error


I am getting the Error 131073 while instatiating the CFB mode when I try to use prefixed IV value. When I change it to random it works, but I need it to be prefixed.

What I have tried gives this error:

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

But when I set the IV to be random I am getting the desired output.

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

How can I use a prefix value for IV?

Note: The Mac_AddressBytes, ip_address_Bytes and DeviceIdBytes are valid values of MAC adress, Ip Adress, DeviceID The values are random generated strings


Solution

  • The error you get is

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

    you have to decode your iv

    iv = base64.b64decode(iv_value)