Click here to Skip to main content
Click here to Skip to main content
Go to top

Calculating hash values in Windows Metro Style applications using C#

, 4 Mar 2013
Rate this:
Please Sign up or sign in to vote.
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 

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).

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.

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

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

IBuffer digest = Algorithm.HashData(vector);

Check for validation:

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:

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)

Share

About the Author

Tyronne Thomas
Software Developer (Senior)
Sri Lanka Sri Lanka
No Biography provided

Comments and Discussions

 
QuestionNice PinmemberJahmani1-Nov-12 0:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 4 Mar 2013
Article Copyright 2012 by Tyronne Thomas
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid