1 using System;
2 using System.Text;
3 using System.Security.Cryptography;
4 using System.IO;
5
6
7
8 //默认密钥向量
9 private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
10 /// <summary>
11 /// DES加密字符串
12 /// </summary>
13 /// <param name="encryptString">待加密的字符串</param>
14 /// <param name="encryptKey">加密密钥,要求为8位</param>
15 /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
16 public static string EncryptDES(string encryptString, string encryptKey)
17 {
18 try
19 {
20 byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
21 byte[] rgbIV = Keys;
22 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
23 DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
24 MemoryStream mStream = new MemoryStream();
25 CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
26 cStream.Write(inputByteArray, 0, inputByteArray.Length);
27 cStream.FlushFinalBlock();
28 return Convert.ToBase64String(mStream.ToArray());
29 }
30 catch
31 {
32 return encryptString;
33 }
34 }
35
36 /// <summary>
37 /// DES解密字符串
38 /// </summary>
39 /// <param name="decryptString">待解密的字符串</param>
40 /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
41 /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
42 public static string DecryptDES(string decryptString, string decryptKey)
43 {
44 try
45 {
46 byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
47 byte[] rgbIV = Keys;
48 byte[] inputByteArray = Convert.FromBase64String(decryptString);
49 DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
50 MemoryStream mStream = new MemoryStream();
51 CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
52 cStream.Write(inputByteArray, 0, inputByteArray.Length);
53 cStream.FlushFinalBlock();
54 return Encoding.UTF8.GetString(mStream.ToArray());
55 }
56 catch
57 {
58 return decryptString;
59 }
60 }
使用方法为:
//获取页面字符串。
var strSource = Request.Forms["xxx"].value;
//加密
var strResult = EncryptDES(strSource,"123456");
//解密
var strRevert = DecryptDES(strResult ,"123456");