Hash with C# in WinRT

In .NET we can use System.Security.Cryptography to generate hash value from a string as the code below:

static void Main(string[] args)
    SHA1 hashAlgorithm = SHA1.Create();
    var str = "Windows 8";
    var encoder = new UTF8Encoding();
    var bytes = encoder.GetBytes(str);

    var hash = Convert.ToBase64String(hashAlgorithm.Hash);

In the example, I use SHA1 algorithm to generate hash value from a UTF8 string, “Windows 8”.


However, in WinRT, we will have to use Windows.Security.Cryptography which has different API for the same task.

Let’s see the code that will generate hash value using the same SHA1 algorithm from the same string, “Windows 8”.

private void Button_Click_1(object sender, RoutedEventArgs e)
    var str = "Windows 8";
    IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8);
    HashAlgorithmProvider hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
    IBuffer hashBuffer = hashAlgorithm.HashData(buffer);

    var strHashBase64 = CryptographicBuffer.EncodeToBase64String(hashBuffer);
    encryptedText.Text = strHashBase64;

Here, I just put the code inside the button click handler for simplicity’s sake. Let’s run it and click the “Encrypt” button.


Hope this short blog helps someone. Enjoy coding!