Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single block AES decryption in Ruby

I need to play around with some AES snippets.

I've got some cipher text c and a key k. The cipher text has been encrypted using AES-CBC, with the IV prepended. No padding is present, the plain text's length is a multiple of 16.

So I'm doing this:

aes = OpenSSL::Cipher::Cipher.new("AES-128-CCB")
aes.decrypt
aes.key = k
aes.iv = c[0..15]
aes.update(c[16..63]) + aes.final

and it's working just fine.

Now I need to do the CBC mode by hand, so I need "plain" AES decryption of a single block.

I'm trying this:

aes = OpenSSL::Cipher::Cipher.new("AES-128-ECB")
aes.decrypt
aes.key = k
aes.iv = c[0..15]
aes.update(c[16..31]) + aes.final

And it fails with

in `final': bad decrypt (OpenSSL::Cipher::CipherError)

How do I do it?

like image 871
Thomas Avatar asked Apr 14 '13 13:04

Thomas


1 Answers

I assume you are getting the final error because it defaults to using padding.

decrypter.padding = 0

Also to do CBC mode manually with ECB mode, setting the IV will do nothing, you need to XOr the decrypted block with the IV (or the previous ciphertext block if you end up decrypting more than one block).

like image 77
jbtule Avatar answered Sep 20 '22 14:09

jbtule