Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming

Calculating hash values in Windows Metro Style applications using C#

5.00/5 (1 vote)
4 Mar 2013CPOL1 min read 24.5K   465  
Calculating hash values in Windows Metro style applications using C# and .NET 4.5.

Introduction

This tip provides you a simple way to create a hash value for a string in Windows Metro style applications.

Background 

In cryptography, hash functions provide three separate functions:

  1. Collision resistance: How hard is it for someone to find two messages (any two messages) that hash the same?
  2. Pre-image resistance: Given a hash, how hard is it to find another message that hashes the same? Also known as a one way hash function.
  3. Second pre-image resistance: Given a message, find another message that hashes the same.

Windows Metro Style applications support the below hashing methods:

  • MD5
  • SHA1
  • SHA256
  • SHA384
  • SHA512

The normal .NET System.Security.Cryptography namespace does not exist in Metro thus we need to use the following namespaces:

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

Using the Code 

Image 1

As the first step, we need to create the hash algorithm provider object as an argument. For the Open Algorithm method, you can pass the hash type of your choice (MD5, SHA1, SHA256, SHA384, and SHA512).

C#
HashAlgorithmProvider Algorithm = HashAlgorithmProvider.OpenAlgorithm("SHA256");

As the second step create a buffer using the CryptographicBuffer class and convert the value that you want to hash.

C#
IBuffer vector = CryptographicBuffer.ConvertStringToBinary(DataString, BinaryStringEncoding.Utf8); 

Using the Algorithm object that you created to hash the data:

C#
IBuffer digest = Algorithm.HashData(vector);

Check for validation:

C#
if (digest.Length != Algorithm.HashLength){
    throw new System.InvalidOperationException("HashAlgorithmProvider failed to generate a hash of proper length!");            
}

Finally get the hash values as a hex string:

C#
dataHash = CryptographicBuffer.EncodeToHexString(digest);
/// <summary>
/// This Method whill create a  Hash for a Given string
/// </summary>
/// <param name="DataString"></param>
/// <returns></returns>
internal string CalculateHashForString(string DataString,string hashType )
{
    string dataHash = string.Empty;

    if (string.IsNullOrWhiteSpace(DataString))
        return null;

    if (string.IsNullOrWhiteSpace(hashType))
        hashType = "MD5";
    try
    {
        ///Hash Algorithm Provider is Created 
        HashAlgorithmProvider Algorithm = HashAlgorithmProvider.OpenAlgorithm(hashType);
        ///Creating a Buffer Stream using the Cryptographic Buffer class and UTF8 encoding 
        IBuffer vector = CryptographicBuffer.ConvertStringToBinary(DataString, BinaryStringEncoding.Utf8);


        IBuffer digest = Algorithm.HashData(vector);////Hashing The Data 

        if (digest.Length != Algorithm.HashLength)
        {
            throw new System.InvalidOperationException(
              "HashAlgorithmProvider failed to generate a hash of proper length!");            
        }else{

            dataHash = CryptographicBuffer.EncodeToHexString(digest);//Encoding it to a Hex String 
        return dataHash;
        }
    }
    catch (Exception ex)
    {
        ///
    }

    return null;
} 

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    try
    {
        if(!string.IsNullOrWhiteSpace(txtValue.Text))
        {
            // Hash Types Supported
            ///MD5
            ///SHA1
            ///SHA256
            ///SHA384
            ///SHA512

            string hashAlgorithm = "SHA256";
            lblAlg.Text = hashAlgorithm;
            lblResult.Text = CalculateHashForString(txtValue.Text, hashAlgorithm);
        }
    }catch(Exception ex)
    {
    }
}

Points of Interest

Please note the sample code is written in .NET 4.5 and it’s a Metro style application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)