密鈅長度有規定,密文長度應該是無限定。註釋中寫的長度是爲了滿足以下需求:密文長度固定。
1 ///<summary>
2 ///DES 加密解密
3 ///Rex Rao @2011-5-13
4 ///</summary>
5 public static class DES
6 {
7 ///<summary>
8 /// DES加密
9 ///</summary>
10 ///<param name="content">8-15bytes明文</param>
11 ///<param name="key">8bytes密鈅</param>
12 ///<returns>32bytes密文</returns>
13 public static string DESEncrypt(string content, string key)
14 {
15 byte[] data = Encoding.ASCII.GetBytes(content);
16 DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
17 DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
18 DES.IV = ASCIIEncoding.ASCII.GetBytes(key);
19 MemoryStream ms = new MemoryStream(); //內存流。
20 CryptoStream cs = new CryptoStream(ms, DES.CreateEncryptor(), CryptoStreamMode.Write);//內存流創建為加密轉換流
21 cs.Write(data, 0, data.Length);
22 cs.FlushFinalBlock(); //用缓冲区的当前状态更新基础数据源或储存库,随后清除缓
23 StringBuilder ret = new StringBuilder();
24 foreach (byte b in ms.ToArray())
25 {
26 ret.AppendFormat("{0:X2}", b);
27 }
28 return ret.ToString();
29 }
30
31 ///<summary>
32 /// DES解密
33 ///</summary>
34 ///<param name="content">32bytes密文</param>
35 ///<param name="key">8bytes密鈅</param>
36 ///<returns>8-15bytes明文</returns>
37 public static string DESDecrypt(string content, string key)
38 {
39 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
40
41 //Put the input string into the byte array
42 byte[] inputByteArray = new byte[content.Length / 2];
43 for (int x = 0; x < content.Length; x += 2)
44 {
45 int i = Convert.ToInt32(content.Substring(x, 2), 16);
46 inputByteArray[x / 2] = (byte)i;
47 }
48
49 des.Key = ASCIIEncoding.ASCII.GetBytes(key);
50 des.IV = ASCIIEncoding.ASCII.GetBytes(key);
51 MemoryStream ms = new MemoryStream();
52 CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
53 //Flush the data through the crypto stream into the memory stream
54 cs.Write(inputByteArray, 0, inputByteArray.Length);
55 cs.FlushFinalBlock();
56
57 //Get the decrypted data back from the memory stream
58 //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象
59 StringBuilder ret = new StringBuilder();
60
61 return System.Text.Encoding.UTF8.GetString(ms.ToArray());
62 }
63 }