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 (, 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. Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
      or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.