jquery

gist JS

Tuesday, December 08, 2009

Decrypting Ruby AES Encryption

Want to encrypt something in Ruby and decrypt it in another language like AS3 using As3Crypto? Sure you can encrypt 'test string' and 'foo, without any problems. But say you want to encode something long.. like 16 character long. After much suffering, the following worked for me.



The main gotcha is that Base64.encode64 has a nasty habit of sprinkling newline characters to your strings. I can't imagine why it does this, particularly when there's a method b64encode(bin, len = 60) that is meant to do this, but I can tell you that AES sure doesn't like you adding random characters to ciphertexts.

Of course rails already thought of this and a method:
encode64s exists. So you could use encode64s instead of encode64, although I would argue that they should have called it something a bit more explicit eg Base64.encode64InAWayThatIsActuallyDecodesToTheSameStringYouStartedWith(string). Just a thought.

Anyway this As3Crypto Demo is a sweet way to test out the decrypt-ability of your encryption complete with all manners of paddings, encryption modes and schemes. Highly recommended.

4 comments:

PDF signature said...

I am new to Ruby and recently assigned a problem that needed me to do AES encryption.And I really agree that smaller strings are easier to deal with than longer ones.Thanks for writing on it.

1w4n said...

Well done! Very useful post.
Thank you.

Mateo said...

I had a bit of a problem with the following line

Base64.encode64(aes(key, string)).gsub /\s/ , ''

Changing it to this worked.

Base64.strict_encode64(aes(key, string))

Using Rails 3.2.3, ruby 1.9.3

Offshore Software Development Company said...

I was exploring for ruby on rails consultants and alighted up on your send and i ought declare thanks for dividing such practical information.