1 // 对称加密帮助类 2 public static class CryptoHelper 3 { 4 //详细参考http://www.cnblogs.com/JimmyZhang/archive/2008/10/02/Cryptograph.html 5 private static ICryptoTransform encryptor; // 加密器对象 6 private static ICryptoTransform decryptor; // 解密器对象 7 8 private static SymmetricAlgorithm provider = SymmetricAlgorithm.Create("TripleDES"); 9 10 private const int BufferSize = 1024;11 12 13 ///14 /// 加密算法15 /// 16 /// 为24或16位字符17 /// 被加密的字符串18 ///19 public static string Encrypt(string key, string encryptedText)20 {21 provider.IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };22 provider.Key = Encoding.UTF8.GetBytes(key);23 24 encryptor = provider.CreateEncryptor();25 // 创建明文流26 byte[] clearBuffer = Encoding.UTF8.GetBytes(encryptedText);27 MemoryStream clearStream = new MemoryStream(clearBuffer);28 29 // 创建空的密文流30 MemoryStream encryptedStream = new MemoryStream();31 32 CryptoStream cryptoStream =33 new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write);34 35 // 将明文流写入到buffer中36 // 将buffer中的数据写入到cryptoStream中37 int bytesRead = 0;38 byte[] buffer = new byte[BufferSize];39 do40 {41 bytesRead = clearStream.Read(buffer, 0, BufferSize);42 cryptoStream.Write(buffer, 0, bytesRead);43 } while (bytesRead > 0);44 45 cryptoStream.FlushFinalBlock();46 47 // 获取加密后的文本48 buffer = encryptedStream.ToArray();49 string str = Convert.ToBase64String(buffer);50 return str;51 }52 53 // 解密算法54 /// 55 /// 56 /// 为24或16位字符57 /// 被解密的字符串58 ///59 public static string Decrypt(string key, string decryptedText)60 {61 provider.IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };62 provider.Key = Encoding.UTF8.GetBytes(key);63 64 decryptor = provider.CreateDecryptor();65 byte[] encryptedBuffer = Convert.FromBase64String(decryptedText);66 Stream encryptedStream = new MemoryStream(encryptedBuffer);67 68 MemoryStream clearStream = new MemoryStream();69 CryptoStream cryptoStream =70 new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read);71 72 int bytesRead = 0;73 byte[] buffer = new byte[BufferSize];74 75 do76 {77 bytesRead = cryptoStream.Read(buffer, 0, BufferSize);78 clearStream.Write(buffer, 0, bytesRead);79 } while (bytesRead > 0);80 81 buffer = clearStream.GetBuffer();82 string str =83 Encoding.UTF8.GetString(buffer, 0, (int)clearStream.Length);84 85 return str;86 }87 88 }