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:
- Collision resistance:
How hard is it for someone to find two messages (any two messages) that hash the same?
- 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.
- 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);
internal string CalculateHashForString(string DataString,string hashType )
{
string dataHash = string.Empty;
if (string.IsNullOrWhiteSpace(DataString))
return null;
if (string.IsNullOrWhiteSpace(hashType))
hashType = "MD5";
try
{
HashAlgorithmProvider Algorithm = HashAlgorithmProvider.OpenAlgorithm(hashType);
IBuffer vector = CryptographicBuffer.ConvertStringToBinary(DataString, BinaryStringEncoding.Utf8);
IBuffer digest = Algorithm.HashData(vector);
if (digest.Length != Algorithm.HashLength)
{
throw new System.InvalidOperationException(
"HashAlgorithmProvider failed to generate a hash of proper length!");
}else{
dataHash = CryptographicBuffer.EncodeToHexString(digest);
return dataHash;
}
}
catch (Exception ex)
{
}
return null;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
try
{
if(!string.IsNullOrWhiteSpace(txtValue.Text))
{
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.