I am trying to encrypt a string using AES cbc 128 but I got this problem every time
self._cipher = factory.new(key, args, kwargs)ValueError: IV must be 16 bytes long
I am using pycrypto library and here is my code,
import base64
from Crypto.Cipher import AES
def pad(m):
return m chr(16-len(m))*(16-len(m))
msg = 'Hello there I am new in Python'
ciph = AES.new("asdfghjkl", AES.MODE_CBC, "asdfghjkl")
enc = ciph.encrypt(pad(msg))
base = base64.b64encode(enc)
print (base)
Whenever I change my key and IV length to 16 bit it worked ... but I want to encrypt the string only with this key and IV which is "asdfghjkl"
I have seen a lot of online websites that encrypt strings same way with any key , IV length .. but I did not figure it ... how does it work>
thanks in advance.
CodePudding user response:
Well Mike as in the comments AES uses a 16 bytes IV and 16, 24 or 32 bytes for the key size , so it is not possible to encrypt the Strings or whatever it was, with a short IV and Key unless u did some tricks for example extend the length with the value of Zeros until it becomes 16 Byte..
You can very simply convert ur password and IV to hex and add zeros until it becomes 16 in ur case the "asdfghjkl" will be in hex "61 73 64 66 67 68 6a 6b 6c " so u will need to add 00000000000000 this way it will work without any errors.. but it is not secure.. in python u can use unhexlify() to convert the hex key and iv to bytes.