1 #region SymmetricAlgorithm加密 2 /// <summary> 3 /// 按指定对称算法、键和向量加密字符串 4 /// </summary> 5 public static byte[] Encrypt(string plainText, string algName, byte[] rgbKey, byte[] rgbIv) 6 { 7 var alg = SymmetricAlgorithm.Create(algName); 8 var transform = alg.CreateEncryptor(rgbKey, rgbIv); 9 var ms = new MemoryStream(); 10 var encStream = new CryptoStream(ms, transform, CryptoStreamMode.Write); 11 var sw = new StreamWriter(encStream); 12 sw.WriteLine(plainText); 13 sw.Close(); 14 encStream.Close(); 15 var buffer = ms.ToArray(); 16 ms.Close(); 17 return buffer; 18 } 19 #endregion 20 #region SymmetricAlgorithm解密 21 /// <summary> 22 /// 按指定对称算法、键和向量解密数据 23 /// </summary> 24 public static string Decrypt(byte[] cypherText, string algName, byte[] rgbKey, byte[] rgbIv) 25 { 26 var alg = SymmetricAlgorithm.Create(algName); 27 var transform = alg.CreateDecryptor(rgbKey, rgbIv); 28 var ms = new MemoryStream(cypherText); 29 var encStream = new CryptoStream(ms, transform, CryptoStreamMode.Read); 30 var sr = new StreamReader(encStream); 31 var val = sr.ReadLine(); 32 sr.Close(); 33 encStream.Close(); 34 ms.Close(); 35 return val; 36 } 37 #endregion