Triple DES In Ruby


#1

With the help of
this(https://www.codeproject.com/articles/14150/encrypt-and-decrypt-data-with-c)
article, we have implemented the triple des encryption in C#.
Implementation is as follows.

public static void Main()
{
string key = “SecretKey”;
string data = “Test Data”;

byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(data);

//If hashing use get hashcode regards to your key
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

//Always release the resources and flush data
// of the Cryptographic service provide. Best Practice
hashmd5.Clear();

TripleDESCryptoServiceProvider tdes = new

TripleDESCryptoServiceProvider();

//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;

//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;

//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdes.CreateEncryptor();

//transform the specified region of bytes array to resultArray
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray,

0, toEncryptArray.Length);

//Release resources held by TripleDes Encryptor
tdes.Clear();

string final_result = Convert.ToBase64String(resultArray, 0,

resultArray.Length);

//Printing the encrypted data into unreadable string format
Console.WriteLine(final_result);

Console.ReadLine();

}

Now We need to implement the same kind of encryption in Ruby. Below is
the code we have tried.

def triple_des_xml_payload(data)
# Get xml payload data and apply triple-des algorithm on it and
convert it to base64
md5 = Digest::MD5.hexdigest(@private_key) # Create a md5 Hash

cipher = OpenSSL::Cipher::Cipher.new('DES-EDE3')
cipher.encrypt
cipher.key = md5
output = cipher.update(data)
output << cipher.final

encrypted_data = Base64.encode64(output)

puts encrypted_data

return encrypted_data

end

Ruby implementation is giving different results.

Can someone help to make this work properly in Ruby as in C#.