0

I dont know PHP and I am stucking at one Position can anybody help me.

I have a code in PHP.

    $binarySignature = hash_hmac('sha1', $stringToSign, $secretKey, true);

    // We need to base64-encode it and then url-encode that.
    $urlSafeSignature = urlencode(base64_encode($binarySignature));

Can anybody tell me what is the code in C# for above code.

3 Answers3

0

Taken mostly from this post:

private string Hash(string message, byte[] secretKey)
{
   byte[] msgBytes = System.Text.Encoding.UTF8.GetBytes(message);
   byte[] hashBytes;
   using (HMACSHA1 hmac = new HMACSHA1(secretKey))
   { 
       hashBytes = hmac.ComputeHash(msgBytes); 
   }
   var sb = new StringBuilder();
   for (int i = 0; i < hashBytes.Length; i++) 
         sb.Append(hashBytes[i].ToString("x2"));
   string hexString = sb.ToString();
   byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(hexString);
   return HttpUtility.UrlEncode(System.Convert.ToBase64String(toEncodeAsBytes));
}
Community
  • 1
  • 1
Nick Pearce
  • 720
  • 5
  • 14
0

It seems that you need something like this:

public string Encode(string input, byte [] key)
{
        HMACSHA1 myhmacsha1 = new HMACSHA1(key);
        byte[] byteArray = Encoding.ASCII.GetBytes( input );
        MemoryStream stream = new MemoryStream( byteArray ); 
        byte[] hashValue = myhmacsha1.ComputeHash(stream);
        return hashValue.ToString();
}

Also, checkout these threads:

How to generate HMAC-SHA1 in C#?

HMAC SHA1 using the same value for key and message

Community
  • 1
  • 1
Oshry
  • 169
  • 3
  • I can't know exactly... but do checkout the above threads, unlike me, they actually explain everything. :) – Oshry Jan 01 '13 at 10:51
0

While calling

using (HMACSHA1 hmac = new HMACSHA1(secretKey,**true**))
   { 
       hashBytes = hmac.ComputeHash(msgBytes); 
   }

we need to pass true as a parameter.for me its working fine.

pganesh21
  • 61
  • 4