How to perform 3DES encryption in Ruby?

668 Views Asked by At

I have a legacy Yii PHP system that is performing 3DES Encryption.

$data = 'id=1,username=admin,[email protected]';
$encrypted_key = mhash(MHASH_SHA1,"foo_bar_key");
$encrypted_value = $StringHelper::encrypt($data, $encrypted_key); 
echo $encrypted_value 
//output => "0G8ITzc32wvqpDIjt6O7tZV9VKwU8KK7p0xI%2Fa%2FjiPOR%2FLrpfvsfMg9fyV2vAHgf"

I'm trying to get this same encrypted value in Ruby using 3DES encryption but I am not able to get it.

require 'openssl'
require 'mhash'
require 'base64'

@data = "id=1,username=admin,[email protected]"
@encrypted_key = Mhash.sha1("foo_bar_key")

cipher = OpenSSL::Cipher::Cipher.new('des-ede-cbc')
cipher.encrypt
cipher.key = @encrypted_key
output = cipher.update(@data)

puts output 
# output => "\xFC\xCAR\xE2L\xB1\x1A\xCA\x83E\x9C\xEEA\xFD\x9D'I\v\x8E9\xFA4\x14\x1F&\xBFR\x8A\xD3\xBDL\xC64\xABf\xCD\x85\x87\x88^"
#Base64.encode64(output) => "/MpS4kyxGsqDRZzuQf2dJ0kLjjn6NBQfJr9SitO9TMY0q2bNhYeIXg==\n"

Does anyone know what I'm doing wrong?

Thanks.

2

There are 2 best solutions below

1
On

I haven't been able to find the $StringHelper::encrypt function, but if it is compatible, you just need to also perform cipher.final in your Ruby code and concatenate the output of update and final as clearly specified in the instructions.

0
On

https://www.ruby-forum.com/topic/168731

'man enc' on my system says:

    des-ede3-cbc       Three key triple DES EDE in CBC mode
    des-ede3           Three key triple DES EDE in ECB mode
  • des3 Alias for des-ede3-cbc

    des-ede3-cfb       Three key triple DES EDE CFB mode
    des-ede3-ofb       Three key triple DES EDE in OFB mode