Share via


HOW-TO: Generate hash in windows store apps

This post shows how to generate hash using SHA1 algorithm in windows store apps, useful if your app makes calls to rest api’s that require app to pass an api signature as header or querystring

 

Import following namespaces 

 using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;

 

Convert the string to binary

 

 IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8);

Create the hash

 

 HashAlgorithmProvider provider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
 //hash it
 IBuffer hash = provider.HashData(buffer);

Create a base64 encoded string

 CryptographicBuffer.EncodeToBase64String(hash);

Base64 encoded string can be used as API signature

 

You can wrap this functionality into a nice helper class and reuse, see full code below 

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using Windows.Security.Cryptography;
 using Windows.Security.Cryptography.Core;
 using Windows.Storage.Streams;
  
 
     internal static class Helper
     {
         public static string ComputeHash(string text)
         {
             string base64Encoded = string.Empty;
             IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8);
             HashAlgorithmProvider provider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
             //hash it
             IBuffer hash = provider.HashData(buffer);
             base64Encoded = CryptographicBuffer.EncodeToBase64String(hash);
             return base64Encoded;
         }
         
     }

Cheers,

</Ram>