1 public class EncryptProvider
2 {
3
4 // Hash an input string and return the hash as
5 // a 32 character hexadecimal string.
6 public static string GetMd5Hash(string input)
7 {
8 MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
9 byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
10 StringBuilder sBuilder = new StringBuilder();
11 for (int i = 0; i < data.Length; i++)
12 {
13 sBuilder.Append(data[i].ToString("x2"));
14 }
15 return sBuilder.ToString();
16 }
17
18 // Verify a hash against a string.
19 public static bool VerifyMd5Hash(string input, string hash)
20 {
21 string hashOfInput = GetMd5Hash(input);
22 StringComparer comparer = StringComparer.OrdinalIgnoreCase;
23 if (0 == comparer.Compare(hashOfInput, hash))
24 {
25 return true;
26 }
27 else
28 {
29 return false;
30 }
31 }
32 //默认密钥向量
33 private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
34 /// <summary>
35 /// DES加密字符串
36 /// </summary>
37 /// <param name="encryptString">待加密的字符串</param>
38 /// <param name="encryptKey">加密密钥,要求为8位</param>
39 /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
40 public static string EncryptDES(string encryptString, string encryptKey)
41 {
42 try
43 {
44 byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
45 byte[] rgbIV = Keys;
46 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
47 DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
48 MemoryStream mStream = new MemoryStream();
49 CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
50 cStream.Write(inputByteArray, 0, inputByteArray.Length);
51 cStream.FlushFinalBlock();
52 return Convert.ToBase64String(mStream.ToArray());
53 }
54 catch
55 {
56 return encryptString;
57 }
58 }
59
60 /// <summary>
61 /// DES解密字符串
62 /// </summary>
63 /// <param name="decryptString">待解密的字符串</param>
64 /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
65 /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
66 public static string DecryptDES(string decryptString, string decryptKey)
67 {
68 try
69 {
70 byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
71 byte[] rgbIV = Keys;
72 byte[] inputByteArray = Convert.FromBase64String(decryptString);
73 DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
74 MemoryStream mStream = new MemoryStream();
75 CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
76 cStream.Write(inputByteArray, 0, inputByteArray.Length);
77 cStream.FlushFinalBlock();
78 return Encoding.UTF8.GetString(mStream.ToArray());
79 }
80 catch
81 {
82 return decryptString;
83 }
84 }
85 }
86
87
88
89