加密
1 public static string GetMd5Hash(string input)
2 {
3 // Create a new instance of the MD5CryptoServiceProvider object.
4 MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
5
6 // Convert the input string to a byte array and compute the hash.
7 byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
8
9 // Create a new Stringbuilder to collect the bytes
10 // and create a string.
11 StringBuilder sBuilder = new StringBuilder();
12
13 // Loop through each byte of the hashed data
14 // and format each one as a hexadecimal string.
15 for (int i = 0; i < data.Length; i++)
16 {
17 sBuilder.Append(data[i].ToString("x2"));
18 }
19
20 // Return the hexadecimal string.
21 return sBuilder.ToString();
22 }
判断是否相等
1 // Verify a hash against a string.
2 public static bool VerifyMd5Hash(string input, string hash)
3 {
4 // Hash the input.
5 string hashOfInput = GetMd5Hash(input);
6
7 if (0 == string.Compare(hashOfInput, hash))
8 {
9 return true;
10 }
11 else
12 {
13 return false;
14 }
15 }
例子
1 static void Main()
2 {
3 string source = "Hello World!";
4
5 string hash = getMd5Hash(source);
6
7 Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");
8
9 Console.WriteLine("Verifying the hash
");10
11 if (verifyMd5Hash(source, hash))
12 {
13 Console.WriteLine("The hashes are the same.");
14 }
15 else
16 {
17 Console.WriteLine("The hashes are not same.");
18 }
19
20 }

浙公网安备 33010602011771号