I’m trying to encrypt some text in rails, and to decrypt the text with
php, and to crypt something with php, and decrypt it with ruby, but I
having problems…
I try to encrypt with ruby, php and openssl console command, the same
text, with the same key, and the same algorithm (AES) but I always got
different results, so whenever I try to decode the text with another
language, I got unwished results
ruby code:
#!/usr/bin/env ruby
require ‘openssl’
text = “abcdefghijklmnopqrstuvwxyz”
key = “altakey”
alg = “AES-128-ECB”
file_name = “test.encrypted”
file_name_2 = “test.decrypted”
puts %(clear text: “#{text}”)
puts %(symmetric key: “#{key}”)
puts %(cipher alg: “#{alg}”)
puts “–Encrypting–”
des = OpenSSL::Cipher::Cipher.new(alg)
des.encrypt(key)
cipher = des.update(text)
cipher << des.final
puts %(encrypted text: #{cipher.inspect})
puts
file = File.open(file_name, “w”)
file.truncate(0)
file << cipher
file.close
The result:
<8C> Ã?nÃLzÃ?¹ª^OÃ^^©|<9F><8A>V¸hq·X<84>±Ã?7tåëÃ?ô
This is the php code:
$text = “abcdefghijklmnopqrstuvwxyz”;
$key = “altakey”;
$alg = “AES-128-ECB”;
$file_name = “test.encrypted”;
$file_name_2 = “test.decrypted”;
echo “decrypted content: $text\n”;
echo “key: $key\n”;
$result = mcrypt_encrypt ( MCRYPT_RIJNDAEL_128 , $key, $text,
MCRYPT_MODE_ECB);
echo “result: $result\n”;
$file = fopen($file_name, “w”);
fwrite($file, $result);
fclose($file);
The result (with a warning):
Warning: mcrypt_encrypt(): Attempt to use an empty IV, which is NOT
recommend in
/usr/local/src/ruby/ruby-1.8.4/sample/openssl/test.encrypt.php on line
13
^_�^<90>S^K<80>¢{^Zò<93>dºEu<98>pñ¢4^\8^M�H<84>S5�åu
And finally, an openssl version:
#!/bin/bash
openssl enc -aes-128-ecb -in test.original -out test.encrypted
The result:
Salted__9Y<80>gÃ^LÃ?<96>}Ã?®4^FÃÃ?lÃ?ÂÃ?Ã?&Ã?Ã?^Sª&֑)±ú9i*Ã?VáI<91>ê
They are throw different results, but the encription algorithm is the
same and the key is the same