AES/CBC/PKCS5Padding implementation in Ruby (for rails)
aes, pkcs#5, pkcs#7, ruby
Solution
The Ruby code in my first post is correct, the problem was this `AES/CBC/PKCS5Padding` used by Java part.
Java program should not use this scheme for `AES-CBC-256`. `PKCS5` pads to a 64 bit (8 byte) block size, but `AES-256-CBC` uses 16 byte blocks. Therefore, `PKCS7` must be used.
Problem
I need to decrypt text encrypted using `AES/CBC/PKCS5Padding` scheme. The encrypted text I got was generated using some Java software. All values below are changed by me to something fictional. What I get is a Key `aHjgYFutF672eGIUGGVlgSETyM9VJj0K` (256-bit = 32-chars * 8-bit) and IV: `rxYoks3c8hRRsL2P` (16-bit) and (I supposed) Base64 encoded encrypted result `ETlAHS5ZcshKxQUaHVB8==` What I need is to decrypt in Ruby this `ETlAHS5ZcshKxQUaHVB8==` to get in the and a simple string, like 'blablablabla' I tried to decrypt what I got using both Ruby and just common linux console openssl command. NOTE: Key and IV below are not the ones used in real code: ``` # require 'openssl' # require 'base64' # decryption aes = OpenSSL::Cipher::AES256.new(:CBC) aes.decrypt aes.padding = 1 # actually it's on by default aes.key = "aHjgYFutF672eGIUGGVlgSETyM9VJj0K" aes.iv="rxYoks3c8hRRsL2P" aes.update(Base64::decode64("ETlAHS5ZcshKxQUaHVB8=="))+aes.final => OpenSSL::Cipher::CipherError: bad decrypt ``` Same as above but in console, key and iv converted to hex with: ``` $ echo -n $key256 | hexdump -e '16/1 "%02x"' $ echo -n $iv | hexdump -e '16/1 "%02x"' $ echo "ETlAHS5ZcshKxQUaHVB8==" | openssl enc -d -aes-256-cbc -a -K 61486a675946757446363732654749554747566c67534554794d39564a6a304b -iv 7278596f6b73336338685252734c3250 bad decrypt 140378046432928:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:539: ``` BTW. to get back original key and iv in the console you an use: ``` $ echo 61486a6... | xxd -r -p #or , but then need to add \x before every character pair $ eval `printf "\x61\x48......" ``` Please give me some clues as I hoped in the beginning that I will be able to use https://github.com/chicks/aes gem. The gem seems fine, it's just a nice wrapper for `OpenSSL::Cipher::Cipher`. Is it possible that ruby/openssl use different PKCS, let's say PKCS#7, Java uses PKCS#5 and I need to preprocess my data ? Or there is a vesion mismatch between ruby/openssl and that Java's PKCS #7 and #5? #5 is meant for 8byte data blocks and #7 is for 16byte? Just a wild guess ...