H
H
hAlex2014-04-19 05:05:38
Python
hAlex, 2014-04-19 05:05:38

How to decrypt a string using PyCrypto?

I'm trying to decode a rail cookie in python, but I ran into difficulties.
iv is decoded from base64.b64decode, a string like this is returned

\xe7^t\xd1\xad\xf7o\x8fw\xf3V\xbby\xa7\x1ei\xce8\xe3}\x1b\xeb\xb7\x9e\x7f\xce^\xe7\xdd\xfd

AES.new(key, AES.MODE_CBC, iv)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/AES.py", line 94, in new
    return AESCipher(key, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/AES.py", line 59, in __init__
    blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__
    self._cipher = factory.new(key, *args, **kwargs)
ValueError: IV must be 16 bytes long

As I understand it, there is some kind of problem with the types, but I don’t know how to solve it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sheknitrtch, 2014-04-19
@sheknitrtch

The problem is that you are using the AES decryption library incorrectly. The error message clearly states that the iv variable must be exactly 16 bytes long. The decryption code should look like this:

key = 'some secret key'
iv = '0123456789012345' #Вектор инициализации.
             #Его длина должна быть 16 байт ровно
ciphertext = '\xe7^t\xd1\xad\xf7o\x8fw\xf3V\xbby\xa7\x1ei\xce8\xe3}\x1b\xeb\xb7\x9e\x7f\xce^\xe7\xdd\xfd'
aes = AES.new(key, AES.MODE_CBC, iv)
text = aes.decrypt(ciphertext)

key is the secret key
iv is the initialization vector . Where to take it in your case - I do not know. This is not a required parameter. As written in the documentation , you can not pass it to the new method.
ciphertext is ciphertext.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question