The following section is copied to msdn and demonstrates how to encrypt and verify the password of a string.
During the development process, we encrypt and store the passwords of new users using MD5 encryption. Then, when users log on, after the user-Entered password is re-encrypted by MD5, it is compared with the encrypted password stored in the database to confirm the user's identity.
Note that MD5 encryption is irreversible (decryption ).
Using system;
Using system. Security. cryptography;
Using system. text;
Class Example
...{
// Hash an input string and return the hash
// A 32 character hexadecimal string.
Static string getmd5hash (string input)
...{
// Create a new instance of the md5cryptoserviceprovider object.
MD5 md5hasher = md5.create ();
// Convert the input string to a byte array and compute the hash.
Byte [] DATA = md5hasher. computehash (encoding. Default. getbytes (input ));
// Create a new stringbuilder to collect the bytes
// And create a string.
Stringbuilder sbuilder = new stringbuilder ();
// Loop through each byte of the hashed data
// And format each one as a hexadecimal string.
For (INT I = 0; I <data. length; I ++)
...{
Sbuilder. append (data [I]. tostring ("X2 "));
}
// Return the hexadecimal string.
Return sbuilder. tostring ();
}
// Verify a hash against a string.
Static bool verifymd5hash (string input, string hash)
...{
// Hash the input.
String hashofinput = getmd5hash (input );
// Create a stringcomparer an comare the hashes.
Stringcomparer comparer = stringcomparer. ordinalignorecase;
If (0 = comparer. Compare (hashofinput, hash ))
...{
Return true;
}
Else
...{
Return false;
}
}
Static void main ()
...{
String source = "Hello world! ";
String hash = getmd5hash (source );
Console. writeline ("the MD5 hash of" + Source + "is:" + hash + ".");
Console. writeline ("verifying the hash ...");
If (verifymd5hash (source, hash ))
...{
Console. writeline ("the hashes are the same .");
}
Else
...{
Console. writeline ("the hashes are not same .");
}
}
}
// This code example produces the following output:
//
// The MD5 hash of Hello world! Is: ed076287532e86365e841e92bfc50d8c.
// Verifying the hash...
// The hashes are the same.