Home > database >  Equivalent of "openssl_encrypt" in Ruby
Equivalent of "openssl_encrypt" in Ruby

Time:10-26

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 # => \x95\xF6\xD6\xF0\x97\x0F\xAB\xA7d\x12y\x98\xD2\x11\xBBW

CodePudding user response:

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({'option':'UTF8','string':'00000000000000000000000000000000'},{'option':'UTF8','string':'0000000000000000'},'CBC','Raw','Hex',{'option':'Hex','string':''})&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 sequence \x

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 be lfbW8JcPq6dkEnmY0hG7Vw==

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 the \x).

CodePudding user response:

I suggest you use Base64#encode64 to get the same result as in your php example.

require 'Base64'
puts Base64.encode64(encrypted) # => lfbW8JcPq6dkEnmY0hG7Vw==
  • Related