MD5 hashing can be used as a quick and easy way to check if a string was changed or not. I created a class to let me get the hash or verify it with 1 line of code.
public class MD5Strings
{
// Hash an input string and return the hash as
// a 32 character hexadecimal string.
public 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 sBuilder.ToString(); // Return the hexadecimal string.
}
// Verify a hash against a string.
public static bool verifyMd5Hash(string input, string hash)
{
string hashOfInput = getMd5Hash(input); // Hash the input.
//Create a StringComparer an comare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
}
Now, to get the hash of a string:
string result;
//return the hash in uppercase to make it a little more presentable
result = MD5Strings.getMd5Hash("Hello, World!").ToUpper();
And to verify a hash:
bool verify = MD5Strings.verifyMd5Hash("Hello, World!",
"65A8E27D8879283831B664BD8B7F0AD4");