• C# AES CBC加密解密


     1         public static string Decrypt(string combinedString, string keyString)
     2         {
     3             string plainText;
     4             byte[] combinedData = Convert.FromBase64String(combinedString);
     5             Aes aes = Aes.Create();
     6             aes.Key = Encoding.UTF8.GetBytes(keyString);
     7             byte[] iv = new byte[aes.BlockSize / 8];
     8             byte[] cipherText = new byte[combinedData.Length - iv.Length];
     9             Array.Copy(combinedData, iv, iv.Length);
    10             Array.Copy(combinedData, iv.Length, cipherText, 0, cipherText.Length);
    11             aes.IV = iv;
    12             aes.Mode = CipherMode.CBC;
    13             ICryptoTransform decipher = aes.CreateDecryptor(aes.Key, aes.IV);
    14 
    15             using (MemoryStream ms = new MemoryStream(cipherText))
    16             {
    17                 using (CryptoStream cs = new CryptoStream(ms, decipher, CryptoStreamMode.Read))
    18                 {
    19                     using (StreamReader sr = new StreamReader(cs))
    20                     {
    21                         plainText = sr.ReadToEnd();
    22                     }
    23                 }
    24 
    25                 return plainText;
    26             }
    27         }
    28 
    29         public static string Encrypt(string plainText, string keyString)
    30         {
    31             byte[] cipherData;
    32             Aes aes = Aes.Create();
    33             aes.Key = Encoding.UTF8.GetBytes(keyString);
    34             aes.GenerateIV();
    35             aes.Mode = CipherMode.CBC;
    36             ICryptoTransform cipher = aes.CreateEncryptor(aes.Key, aes.IV);
    37 
    38             using (MemoryStream ms = new MemoryStream())
    39             {
    40                 using (CryptoStream cs = new CryptoStream(ms, cipher, CryptoStreamMode.Write))
    41                 {
    42                     using (StreamWriter sw = new StreamWriter(cs))
    43                     {
    44                         sw.Write(plainText);
    45                     }
    46                 }
    47 
    48                 cipherData = ms.ToArray();
    49             }
    50 
    51             byte[] combinedData = new byte[aes.IV.Length + cipherData.Length];
    52             Array.Copy(aes.IV, 0, combinedData, 0, aes.IV.Length);
    53             Array.Copy(cipherData, 0, combinedData, aes.IV.Length, cipherData.Length);
    54             return Convert.ToBase64String(combinedData);
    55         }
  • 相关阅读:
    CSS处理小技巧
    React 脚手架构建
    Tomcat8学习
    javaScript(ES5中的类,原型,原型对象和函数对象的关系)
    保留两位小数(逢5进位,精度不会丢失)
    获取过去12个月
    mybatis 踩坑记录
    动态代理--jdk和cglib
    lambda表达式
    mybatis的mapper映射配置文件详解
  • 原文地址:https://www.cnblogs.com/dongzhaosheng/p/16315741.html
Copyright © 2020-2023  润新知