/// /// 加密 /// public static class Encrypting { #region 使用對稱加密、解密 private static string GetEncryptKey() { return ConfigurationManager.AppSettin... ...
/// <summary> /// 加密 /// </summary> public static class Encrypting { #region 使用對稱加密、解密 private static string GetEncryptKey() { return ConfigurationManager.AppSettings["EncryptKey"]; } /// <summary> /// 使用對稱演算法加密 /// </summary> /// <param name="str"></param> /// <param name="encryptKey"></param> /// <returns></returns> public static string SymmetricEncrypts(string str) { string result = string.Empty; byte[] inputData = System.Text.Encoding.UTF8.GetBytes(str); SymmetricAlgorithm Algorithm = null; MemoryStream msTarget = null; CryptoStream encStream = null; try { byte[] kv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; //如需指定加密演算法,可在Create()參數中指定字元串 //Create()方法中的參數可以是:DES、RC2 System、Rijndael、TripleDES //採用不同的實現類對IV向量的要求不一樣(可以用GenerateIV()方法生成),無參數表示用Rijndael Algorithm = SymmetricAlgorithm.Create();//產生一種加密演算法 msTarget = new MemoryStream(); //定義將數據流鏈接到加密轉換的流。 encStream = new CryptoStream(msTarget, Algorithm.CreateEncryptor(Convert.FromBase64String(GetEncryptKey()), kv), CryptoStreamMode.Write); encStream.Write(inputData, 0, inputData.Length); encStream.FlushFinalBlock(); result = Convert.ToBase64String(msTarget.ToArray()); } catch (Exception) { return null; } finally { if (Algorithm != null) Algorithm.Clear(); if (msTarget != null) msTarget.Close(); if (encStream != null) encStream.Close(); } return result; } /// <summary> /// 使用對稱演算法解密 /// </summary> /// <param name="encryptStr"></param> /// <param name="encryptKey"></param> /// <returns></returns> public static string SymmectricDecrypts(string encryptStr) { string result = string.Empty; SymmetricAlgorithm Algorithm = null; MemoryStream msTarget = null; CryptoStream decStream = null; //加密時使用的是Convert.ToBase64String(),解密時必須使用Convert.FromBase64String() try { byte[] kv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byte[] encryptData = Convert.FromBase64String(encryptStr); Algorithm = SymmetricAlgorithm.Create(); msTarget = new MemoryStream(); decStream = new CryptoStream(msTarget, Algorithm.CreateDecryptor(Convert.FromBase64String(GetEncryptKey()), kv), CryptoStreamMode.Write); decStream.Write(encryptData, 0, encryptData.Length); decStream.FlushFinalBlock(); result = System.Text.Encoding.Default.GetString(msTarget.ToArray()); } catch (Exception) { return null; } finally { if (Algorithm != null) Algorithm.Clear(); if (msTarget != null) msTarget.Close(); if (decStream != null) decStream.Close(); } return result; } #endregion }