I am trying to convert this PHP code to Ruby but the result is not the same. What am I doing wrong?
PHP
$iv = str_repeat('0', 16);
$passphrase = str_repeat('0', 32);
$encrypted = openssl_encrypt('Hello', 'AES-256-CBC', $passphrase, 0, $iv);
echo $encrypted; // => lfbW8JcPq6dkEnmY0hG7Vw==
Ruby
cipher = OpenSSL::Cipher.new('AES-256-CBC').encrypt
cipher.iv = '0' * 16
cipher.key = '0' * 32
encrypted = cipher.update('Hello') + cipher.final
puts encrypted # => x95xF6xD6xF0x97x0FxABxA7dx12yx98xD2x11xBBW
2
Answers
The result is basically the same.
If you try to encode AES 256 CBC, you can follow this link : https://gchq.github.io/CyberChef/#recipe=AES_Encrypt(%7B'option‘:’UTF8′,’string’:’00000000000000000000000000000000’%7D,%7B’option’:’UTF8′,’string’:’0000000000000000’%7D,’CBC’,’Raw’,’Hex’,%7B’option’:’Hex’,’string’:”%7D)&input=SGVsbG8
As you can see I have encoded "hello" into AES CBC with your Key and IV (both in UTF8)
The result in HEX format is
95f6d6f0970faba764127998d211bb57
which basically matches the Rails string minus the escape sequencex
Now the PHP string is a bit different but it is because it has been BASE 64 encoded.
You can go here https://base64.guru/converter/encode/hex and copy
95f6d6f0970faba764127998d211bb57
into the top box, the result will belfbW8JcPq6dkEnmY0hG7Vw==
EDIT
Just notice the Rails string being slightly different to Hex provided by CyberChef in the last characters. Maybe someone can give more details about Rails notation being slightly different than the HEX, together with the escape sequence
x
. I have read this is common to C language (Ruby is coded in C which may explain the C notation with thex
).I suggest you use Base64#encode64 to get the same result as in your php example.