/// <summary> /// 加密 /// </summary> /// <param name="algorithm">算法</param> /// <param name="valueToEnCrypt">加密值</param> /// <returns>结果</returns> private static string EnCrypt(SymmetricAlgorithm algorithm, string valueToEnCrypt) { byte[] bytes = Encoding.UTF8.GetBytes(valueToEnCrypt); string encryptionKey = EncryptionKey; byte[] originalArray = Encoding.ASCII.GetBytes(encryptionKey); algorithm.Key = (byte[])ArrayFunctions.ReDim(originalArray, algorithm.Key.Length); algorithm.IV = (byte[])ArrayFunctions.ReDim(originalArray, algorithm.IV.Length); StringBuilder builder; using (var stream = new MemoryStream()) { using (var stream2 = new CryptoStream(stream, algorithm.CreateEncryptor(), CryptoStreamMode.Write)) { stream2.Write(bytes, 0, bytes.Length); stream2.FlushFinalBlock(); } builder = new StringBuilder(); for (int i = 0; i < stream.ToArray().Length; i++) { byte num2 = stream.ToArray()[i]; builder.AppendFormat("{0:X2}", num2); } } return(builder.ToString()); }
/// <summary> /// 解密 /// </summary> /// <param name="algorithm">算法</param> /// <param name="valueToDeCrypt">解密值</param> /// <returns>结果</returns> private static string DeCrypt(SymmetricAlgorithm algorithm, string valueToDeCrypt) { var buffer = new byte[valueToDeCrypt.Length / 2]; for (int i = 0; i < (valueToDeCrypt.Length / 2); i++) { int num2 = Convert.ToInt32(valueToDeCrypt.Substring(i * 2, 2), 0x10); buffer[i] = (byte)num2; } string encryptionKey = EncryptionKey; byte[] bytes = Encoding.ASCII.GetBytes(encryptionKey); algorithm.Key = (byte[])ArrayFunctions.ReDim(bytes, algorithm.Key.Length); algorithm.IV = (byte[])ArrayFunctions.ReDim(bytes, algorithm.IV.Length); StringBuilder builder; using (var stream = new MemoryStream()) { using (var stream2 = new CryptoStream(stream, algorithm.CreateDecryptor(), CryptoStreamMode.Write)) { stream2.Write(buffer, 0, buffer.Length); stream2.FlushFinalBlock(); } builder = new StringBuilder(); for (int j = 0; j < stream.ToArray().Length; j++) { builder.Append((char)stream.ToArray()[j]); } } return(builder.ToString()); }