Search code examples
rubyencryptionopenssl3des

How to perform Triple DES calculations in Ruby in hexadecimal?


I'm trying to do some triple DES encryption in Ruby. I'm trying to replicate the results from this page: http://da.nmilne.com/des.html

I'm trying to replicate those result in Ruby. I suspect the problem is the key is supposed to be a string, but I need to pass in a Hexadecimal key. Either that or the string being encrypted is in the wrong format. Or maybe both. :-)

require 'openssl'
des = OpenSSL::Cipher::Cipher.new("des-ede-cbc")
des.encrypt
des.key="23232323232323234545454545454545"
des.update("0000000000000000")
res=des.final
res.unpack('H*')  
=> ["5045c5d37ca4d13b"]

But it should be:

=> ["3a42d7a1d1c60c40"]

Any pointers on where I'm going wrong?


Solution

  • The key is in hex - if you look at the Java page you pasted you can see that easily by decoding the binary values for the key in the detailed output.

    >> des_cbc=OpenSSL::Cipher::Cipher.new("des-ede-cbc")
    => #<OpenSSL::Cipher::Cipher:0x10116ce28>
    >> des_cbc.encrypt
    => #<OpenSSL::Cipher::Cipher:0x10116ce28>
    >> des_cbc.key="\x23"*8 << "\x45"*8
    => "########EEEEEEEE"
    >> des_cbc.update("\x00"*8).unpack('H*')
    => ["3a42d7a1d1c60c40"]