0

I'd like to use Ruby to decrypt a string that's encrypted with PHP. The same decryption logic works fine with PHP, but the Ruby code returns garbage.

The working PHP example:

<?php

$_RIJNDAEL_KEY_ = "uUxJIpSKMbOQQdtm6Y4rPEXeE9TAKUns";
$_RIJNDAEL_IV_ = "PiToVoRjwlg8UwxUxQKI4w==";
$ciphertext = 'T353/s48iKzAf61b2dCOnqUApYa4xxjye8he4oAtJHyyCKl8sCbI33hfP6IqOsQZEIWeQBCsvy97xwJMPD8RwLG4J0wgX9Ihlti1vMar+5nrLrCR4lAfZcoJopoBt1JVnDAojLW+y0S0y5c4GCdB8YrHzj4jv70dg3yX8DxlAWE=';


$content = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $_RIJNDAEL_KEY_, base64_decode($ciphertext), MCRYPT_MODE_ECB, $_RIJNDAEL_IV_);
echo $content . "\n";

?>

The not-working Ruby example:

require "openssl"
require "digest"
require "uri"
require "base64"

data = Base64.decode64("T353/s48iKzAf61b2dCOnqUApYa4xxjye8he4oAtJHyyCKl8sCbI33hfP6IqOsQZEIWeQBCsvy97xwJMPD8RwLG4J0wgX9Ihlti1vMar+5nrLrCR4lAfZcoJopoBt1JVnDAojLW+y0S0y5c4GCdB8YrHzj4jv70dg3yX8DxlAWE=")
key = Base64.decode64('uUxJIpSKMbOQQdtm6Y4rPEXeE9TAKUns')
iv = Base64.decode64('PiToVoRjwlg8UwxUxQKI4w==')
aes = OpenSSL::Cipher.new('AES-128-ECB')

aes.decrypt
aes.padding = 0
aes.key = key
aes.iv = iv

plain = aes.update(data) + aes.final
puts plain

Could anyone shed some light ? Thanks.

1 Answers1

0

Everything here is correct. But. It is necessary to use AES-256-ECB in your example.

Here the code which is runnable:

require "openssl"
require "digest"
require "uri"
require "base64"

data = 'T353/s48iKzAf61b2dCOnqUApYa4xxjye8he4oAtJHyyCKl8sCbI33hfP6IqOsQZEIWeQBCsvy97xwJMPD8RwLG4J0wgX9Ihlti1vMar+5nrLrCR4lAfZcoJopoBt1JVnDAojLW+y0S0y5c4GCdB8YrHzj4jv70dg3yX8DxlAWE='
key = "uUxJIpSKMbOQQdtm6Y4rPEXeE9TAKUns"
#iv = 'PiToVoRjwlg8UwxUxQKI4w=='
aes = OpenSSL::Cipher::AES.new(256, :ECB)

#  Without padding checksum|4033315172 will be truncated!
aes.padding = 0
aes.decrypt
aes.key = key
#aes.iv = iv

plain = aes.update(data.unpack('m')[0]) + aes.final

After decrypt I've got the following:

=> "date_add|2015-01-28 01:36:17\xC2\xA4id_lang|1\xC2\xA4id_currency|1\xC2\xA4id_guest|12165\xC2\xA4id_connections|10668\xC2\xA4checksum|4033315172\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

Next. Without zero-padding in this example, last character of checksum will be truncated. If possible, don't use EBC mode. Here is why.

And finally, you don't need IV in this example. Good luck!

sashaegorov
  • 1,821
  • 20
  • 26
  • Genius! but may I ask why use AES-256-ECB is the Ruby example ? – inthecloud Jan 28 '15 at 10:32
  • @inthecloud Here are good readings about this: - http://stackoverflow.com/questions/1864700/part-ii-how-to-make-ruby-aes-256-cbc-and-php-mcrypt-rijndael-128-play-well-toge - http://www.chilkatsoft.com/p/php_aes.asp – sashaegorov Jan 28 '15 at 11:29