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!


5 thoughts on “Hash with C# in WinRT

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s