标签:
由于涉及到功能是数据加密。所以,在经过小伙伴的查询和测试,我也查询了一些资料来总结一下常用的数据加密算法。
1 static void Main(string[] args)
2 {
3 string source = "Hello World!";
4 using (MD5 md5Hash = MD5.Create())
5 {
6 string hash = GetMd5Hash(md5Hash, source); //对字符串进行加密
7
8 Console.WriteLine("The MD5 hash of " + source + " is: " + hash + "."); //输出加密后的字符串
9
10 Console.WriteLine("Verifying the hash..."); //对加密后的字符串进行验证
11
12 if (VerifyMd5Hash(md5Hash, source, hash)) //判断是否一致
13 {
14 Console.WriteLine("The hashes are the same.");
15 Console.ReadKey();
16 }
17 else
18 {
19 Console.WriteLine("The hashes are not same.");
20 Console.ReadKey();
21 }
22 }
23 }
24
25 #region "MD5加密"
26 static string GetMd5Hash(MD5 md5Hash, string input)
27 {
28
29 // 将输入字符串转换为字节数组,然后计算哈希值。
30 byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
31
32 // 创建新的数据收集字节
33 // 创建一个字符串。
34 StringBuilder sBuilder = new StringBuilder();
35
36 // 通过散列数据的每个字节的环
37 // 和每一个的一个十六进制字符串格式。
38 for (int i = 0; i < data.Length; i++)
39 {
40 sBuilder.Append(data[i].ToString("x2"));
41 }
42
43 // 返回十六进制字符串。
44 return sBuilder.ToString();
45 }
46 #endregion
47
48
49
50
51 #region "验证加密的字符是否一致"
52 // 验证一个字符串的哈希值。
53 static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
54 {
55 //散列输入。
56 string hashOfInput = GetMd5Hash(md5Hash, input);
57
58 // 创建一个比较哈希StringComparer。
59 StringComparer comparer = StringComparer.OrdinalIgnoreCase;
60
61 if (0 == comparer.Compare(hashOfInput, hash)) //进行比较,类似于登陆时比对数据库中的密码
62 {
63 return true;
64 }
65 else
66 {
67 return false;
68 }
69 }
70 #endregion
标签:
原文地址:http://www.cnblogs.com/tgb520-why/p/5545409.html