Hash values

Computing a hash creates a fixed-length numeric value from a byte array. A hash maps a variable-length binary string to a fixed-length binary string. A hash cannot be used for two-way conversion. When you apply a hash algorithm, each character gets hashed into a different binary string.

In the following example, we use the SHA1Managed algorithm to compute the hash. We compute the hash twice to check whether the result is the same. As mentioned earlier, this method is used to maintain data integrity.

In the following code, we are using the UnicodeEncoding class to convert the text to a byte array, and the SHA1Managed algorithm to compute the hash for the byte array. Once converted, we display each and every hashed byte on the screen. To validate the hash, we recompute the hash on the string and compare the hash values. This is one way to validate input data:

public static void HashvalueSample(string texttoEncrypt)
{
UnicodeEncoding uc = new UnicodeEncoding();
Console.WriteLine("Converting to bytes from text");
byte[] databytes = uc.GetBytes(texttoEncrypt);
byte[] computedhash = new SHA1Managed().ComputeHash(databytes);
foreach (byte b in computedhash)
{
Console.Write("{0} ", b);
}
Console.WriteLine("Press any key to continue...");
byte[] reComputedhash = new SHA1Managed().ComputeHash(databytes);
bool result = true;
for (int x = 0; x < computedhash.Length; x++)
{
if (computedhash[x] != reComputedhash[x])
{
result = false;
}
else
{
result = true;
}
}

if (result)
{
Console.WriteLine("Hash value is same");
}
else
{
Console.WriteLine("Hash value is not same");
}
}

The main method for invoking the hash value example is as follows. Here, we just call the helper method that performs the hash compute on the text provided:

static void Main(string[] args)
{
#region Hashvalue
EncryptDecryptHelper.HashvalueSample("This a sample text for hashvalue sample");
#endregion


// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}

When we compute the hash, we display the result and then we undertake a comparison to see whether the result from both calls is the same:

The preceding screenshot shows the program where you compute the hash and display the hashed array. Also, when the program recomputes the hash and effects a comparison, you see the same hash value message.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.235.144