Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES128-CBC "bad magic number" and "error reading input file"

I am trying to decrypt a file (part444.txt) with message:

y2EdLtmNQsZkvwwf8jf3fM6c1thfzF0sQfblayGIBik=

This is base64 encoded encrypted text under 128 bit AES in CBC mode. It is not padded. The IV is the first 16 bytes of the encrypted text and the key is h4ckth1sk3yp4d16.

I know that people received the bad magic number error from problems with Base64 but now I get the "error reading input file" and not sure where to go from here.

I have tried:

openssl enc -base64 -d part444.txt | openssl aes-128-cbc -d -k h4ckth1sk3yp4d16

Why am I encountering the errors "bad magic number" and "error reading input file"?

like image 803
Alex Park Avatar asked Oct 22 '16 03:10

Alex Park


1 Answers

This is sort of a pain to do with openssl, because openssl's encryption makes assumptions about padding and deriving a salted key from the entered password that you have to deliberately turn off.

It's much easier to do in python with say PyCrypto, where these assumptions aren't made.

>>> import base64
>>> data = base64.b64decode('y2EdLtmNQsZkvwwf8jf3fM6c1thfzF0sQfblayGIBik=')
>>> from Crypto.Cipher import AES
>>> aes_crypter = AES.new('h4ckth1sk3yp4d16',  AES.MODE_CBC, data[:16])
>>> aes_crypter.decrypt(data[16:]) # this gives the encrypted secret.

It is possible to do this with openssl, but you have to read the base64 encoded data -- take out the first 16 bytes and remember it as your $IV (after encoding it back to hex that openssl expects), start reading all the bytes after the first 16 and remember it as the $CIPHERTEXT (and say re-encode in base64). Similar for the $KEY, you have to convert it from ASCII to bytes in hex. Assuming you stored these in variables, then the following would work:

IV=`base64 -d part444.txt | xxd -p -l 16`
CIPHERTEXT=`base64 -d part444.txt | cut -b 17- | base64`
KEY=`echo -n h4ckth1sk3yp4d16 |xxd -p`

echo $CIPHERTEXT | openssl aes-128-cbc -d -a  -nopad -K $KEY -iv $IV && echo ""

Note base64 -d decodes base64 to binary (using base64 from GNU coreutils; on BSD replace with base64 -D), base64 b64 encodes binary data, cut -b 17- reads from the 17th byte of data to the end of the file, and xxd -p converts binary to hex.

like image 66
dr jimbob Avatar answered Sep 30 '22 15:09

dr jimbob