Click here to Skip to main content
15,883,883 members
Articles / General Programming

Calculating hash values in Windows Metro Style applications using C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
4 Mar 2013CPOL1 min read 24K   465   8  
Calculating hash values in Windows Metro style applications using C# and .NET 4.5.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace HashSampleMetro
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }


        /// <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)
           {

           }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer (Senior)
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions