user15114148
user15114148

Reputation:

Python3 PyCrypto - ValueError: IV must be 16 bytes long

I am experimenting with the PyCrypto library. My friend gave me the public key (base64) they used to encrypt a string, the ciphertext, and the IV. The cipher they used was AES-CBC. I thought this would be relatively straightforward, but I am getting the error ValueError: IV must be 16 bytes long. Below are my code, traceback, and findings:

CODE:

import sys
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

message = "GgFyMNGjCOnrE3NjNEYko57ZUdy36ldB+/WrR5+ctN6jglicmb3ONvY4mfswk09BUmm0rCBy6yyaTFWKWuEgnMtu0RpbyyHICCQAVTmgwtgQ9wWlE1BJJAHJsZd61cMlsLomtRtCuNOnX5fnoGcs2X=="

key = b'xSAU2gWfDhWusUPplf8RtWknJ0ZKZ+dqK23/go8i0ls='
print(sys.getsizeof(key))

iv = b'WmiBaaAuyX7YCSTTPj07/c=='
print(sys.getsizeof(iv))

aes = AES.new(key, AES.MODE_CBC, iv)
decd = aes.decrypt(message)
print(decd)

TRACE:

77
65
Traceback (most recent call last):
  File "main.py", line 21, in <module>
    aes = AES.new(key, AES.MODE_CBC, iv)
  File "/usr/local/lib/python3.7/site-packages/Crypto/Cipher/AES.py", line 95, in new
    return AESCipher(key, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/Crypto/Cipher/AES.py", line 59, in __init__
    blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__
    self._cipher = factory.new(key, *args, **kwargs)
ValueError: IV must be 16 bytes long

As you can see, the key size is 77 bytes, and the IV size is 65 bytes. I am simply using the key and the IV that was provided to me that encrypted the original text (I am aware of the security implications of putting keys in plain-text. These are not the actual keys, just random strings of the same length for demonstration purposes).

Upvotes: 0

Views: 2975

Answers (1)

KMG
KMG

Reputation: 1501

You need to decode both the key and iv but also you have to decode the message otherwise it wont be 16 bytes aligned as you are using CBC mode.

from Crypto.Cipher import AES
import base64

message = b"GgFyMNGjCOnrE3NjNEYko57ZUdy36ldB+/WrR5+ctN6jglicmb3ONvY4mfswk09BUmm0rCBy6yyaTFWKWuEgnMtu0RpbyyHICCQAVTmgwtgQ9wWlE1BJJAHJsZd61cMlsLomtRtCuNOnX5fnoGcs2X=="
message = base64.b64decode(message)

key = b'xSAU2gWfDhWusUPplf8RtWknJ0ZKZ+dqK23/go8i0ls='
key = base64.b64decode(key)

iv = b'WmiBaaAuyX7YCSTTPj07/c=='
iv = base64.b64decode(iv)

aes = AES.new(key, AES.MODE_CBC, iv)
decd = aes.decrypt(message)
print(decd)

Upvotes: 3

Related Questions