olleh
olleh

Reputation: 1277

Convert C# to Ruby - MD5 and Base 64 a String

I have this code that I need to convert to ruby, this snippet is to create a security key used for a particular API. The string that I am encrypting is a JSON object.

Should I use Digest::MD5.hexdigest() or Digest::MD5.digest()?

C# Code

string strResponse = "[{\"Key\":\"BookNumber\", \"Value\"=>\"BJAK123\"},{\"Key\"=>\"AuthorCode\", \"Value\"=>\"BNA123\"}]";

using (MD5 md5 = MD5.Create())
{
    byte[] bPayload = Encoding.UTF8.GetBytes(strPayload);
    byte[] bPayloadHash = md5.ComputeHash(bPayload);

    strPayloadBase64 = Convert.ToBase64String(bPayloadHash);
}

Ruby Code

payload = [{"Key"=>"BookNumber", "Value"=>"BJAK123"},{"Key"=>"AuthorCode", "Value"=>"BNA123"}]


utf8_params = payload.to_json.force_encoding("iso-8859-1").force_encoding("utf-8")
payload_base64 = Base64.encode64(Digest::MD5.hexdigest(utf8_params))

Upvotes: 1

Views: 414

Answers (1)

Wand Maker
Wand Maker

Reputation: 18772

Use

payload_base64 = Digest::MD5.base64digest(utf8_params)

as Digest::MD5.hexdigest produces a hex string of digest, whereas C# code is performing base64 encoding of the digest.

Upvotes: 2

Related Questions