Showing posts with label Hash Algoritham. Show all posts
Showing posts with label Hash Algoritham. Show all posts

Thursday, February 21, 2008

MD5CryptoServiceProvider C#

System.Security.Cryptography.MD5CryptoServiceProvider is a class that derives from MD5 and helps create hashes.

To create a hash of a string for storing in a data store, we make use of either the CryptoServiceProvider classes in the System.Security.Cryptography namespace, or the FormsAuthentication.HashPasswordForStoringInConfigFile method. Today we'll have a look at how to create a hash for a zip file using the MD5 algorithm.

In our case we are comparing a php generated md5 with a new md5 that we create.This function checks the download completion status of a zip file.

We already have an md5 for the whole zip file.Once we have downloaded the file we again check if the file has been downloaded completely generating an md5 for the downloaded file and then comparing with the md5 that we already have in hand.

private bool Comparemd5()
{
Console.WriteLine("Checking md5 Strings");

string gotmd5String = "";
gotmd5String = _md5String;//got md5 value from server along with the zip

MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
FileStream f = new FileStream(
Application.StartupPath + "\\abc.zip",
FileMode.Open, FileAccess.Read, FileShare.Read, 8192);

md5.ComputeHash(f);

f.Close();

///calculating the md5 of the abc.zip
Byte[] hash = md5.Hash;
StringBuilder buff = new StringBuilder();

foreach (Byte hashByte in hash)
buff.Append(hashByte.ToString("X2").ToLower());

if (gotmd5String.Contains(buff.ToString()))
return true;
else
return false;
}

MD5 are normally irreversible.So when we have to check the new value with an already saved md5 value then we always generate the md5 for that and compare both.

Like for example : a password string.In some applications the password will be stored as md5.So when the user comes back to login.We generate md5 for the password that he/she enters and then compare that with the value that we already have in hand.

Hope this example provides you an easy access for the md5 comparison.

Cheers...