Sunday, November 2, 2014

Calculating a SHA256 hash in .NET [SNIPPET]

As the programming world moves toward REST API for software interactions, we find the need for securing our requests becoming more apparent.
Some 3rd party APIs you consume specify a computed hash to verify the caller’s authenticity, such as Facebook’s “app secret proof” querystring parameter (https://developers.facebook.com/docs/graph-api/securing-requests/), which utilizes a SHA256 hash of the access token and client secret. They demonstrate the ability to compute this hash with PHP:

$appsecret_proof= hash_hmac('sha256', $access_token, $app_secret);

So, I figured it would be useful to demonstrate one way to do this with C# and .NET:

public static string ComputeHmacSha256Hash(string valueToHash, string key)
{
    byte[] keyBytes = Encoding.ASCII.GetBytes(key);
    byte[] valueBytes = Encoding.ASCII.GetBytes(valueToHash);
    byte[] tokenBytes = new HMACSHA256(keyBytes).ComputeHash(valueBytes);
    valueBytes = null;
    keyBytes = null;

    StringBuilder token = new StringBuilder();
    foreach (byte b in tokenBytes)
    {
        token.AppendFormat("{0:x2}", b);
    }
    tokenBytes = null;

    return token.ToString();
}


In the Facebook app secret proof scenario, the “valueToHash” is the access token, and the “key” is the OAuth API key’s client secret.
HMACSHA256 is in the System.Security.Cryptography namespace, and obviously Encoding.ASCII is in System.Text.

1 comment: