olleh
olleh

Reputation: 1277

Convert C# to Ruby - HMAC SHA256 function

I'm trying to get the HMAC SHA256 value(str_signature), I followed the Ruby code from this post, although his example was converting code from Java(with a Hex key).

C#

string strRawSignature = "200123123891:12|11231231|GET|just%20test%20value"

// Convert signature to byte array in order to compute the hash
byte[] bSignature = Encoding.UTF8.GetBytes(strRawSignature);

// Convert ApiKey to byte array - for initializing HMACSHA256
byte[] bSecretKey = Convert.FromBase64String(strApiKey);

string strSignature = "";
using (HMACSHA256 hmac = new HMACSHA256(bSecretKey))
{
    // Compute signature hash
    byte[] bSignatureHash = hmac.ComputeHash(bSignature);

    // Convert signature hash to Base64String for transmission
    str_signature = Convert.ToBase64String(bSignatureHash);
}

Ruby

require "openssl"
require "base64"

digest = OpenSSL::Digest.new('sha256')
key = [ 'xiIm9FuYhetyijXA2QL58TRlvhuSJ73FtdxiSNU2uHE=' ]

#this is just a dummy signature to show what the possible values are
signature = "200123123891:12|11231231|GET|just%20test%20value"

hmac = OpenSSL::HMAC.digest(digest, key.pack("m*"), signature)
str_signature = Base64.urlsafe_encode64(hmac)
example result: "B0NgX1hhW-rsnadD2_FF-grcw9pWghwMWgG47mU4J94="

Update:

  1. Changed the pack method to output base64 strings.

  2. Edited variable names for concistency

References:

  1. Used hexdigest, has a different ouput string length.
  2. This example uses the digest method, although I'm not sure what value the key parameter has, hopefully it's a base 64 encoded string.
  3. This uses hexdigest again. I am pretty sure that digest is the method to go vs hexdigest, since hexdigest ouput has a longer string compared to the sample HMAC value I have from C# script.

Upvotes: 2

Views: 1969

Answers (1)

olleh
olleh

Reputation: 1277

Finally got the monkey of my back!

I don't really need to create a sha256 digest object after all, I just had to put the 'sha256' parameter.

require 'openssl'
require "base64"
#API_KEY = base64 encoded string
key = Base64.decode64(API_KEY)
hash  = OpenSSL::HMAC.digest('sha256', key, "Message")
puts Base64.encode64(hash)

thanks to this link

Upvotes: 2

Related Questions