C# AES的128位、192位、256位加密

您所在的位置:网站首页 密钥多少位数 C# AES的128位、192位、256位加密

C# AES的128位、192位、256位加密

2023-09-06 19:39| 来源: 网络整理| 查看: 265

  AES加密原理,这里就不解释了,自行百度。这里主要细说AES的CBC加密模式下的128位、192位、256位加密区别,参考 对称加密和分组加密中的四种模式(ECB、CBC、CFB、OFB) 。

       这三种的区别,主要来自于密钥的长度,16位密钥=128位,24位密钥=192位,32位密钥=256位。

  废话不多说,直接上图。

 

  16位密钥对应128位加密

  

       

  

 

  24位密钥对应192位加密

  

      

 

     

     32位密钥对应256位加密

   

     

     

   其中,向量都必须是16位。

   

   最后贴出封装的加解密代码:

    

          //AES加密      public static string AesEncrypt(string value, string key, string iv = "") { if (string.IsNullOrEmpty(value)) return string.Empty; if (key == null) throw new Exception("未将对象引用设置到对象的实例。"); if (key.Length < 16) throw new Exception("指定的密钥长度不能少于16位。"); if (key.Length > 32) throw new Exception("指定的密钥长度不能多于32位。"); if (key.Length != 16 && key.Length != 24 && key.Length != 32) throw new Exception("指定的密钥长度不明确。"); if (!string.IsNullOrEmpty(iv)) { if (iv.Length < 16) throw new Exception("指定的向量长度不能少于16位。"); } var _keyByte = Encoding.UTF8.GetBytes(key); var _valueByte = Encoding.UTF8.GetBytes(value); using (var aes = new RijndaelManaged()) { aes.IV = !string.IsNullOrEmpty(iv) ? Encoding.UTF8.GetBytes(iv) : Encoding.UTF8.GetBytes(key.Substring(0, 16)); aes.Key = _keyByte; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; var cryptoTransform = aes.CreateEncryptor(); var resultArray = cryptoTransform.TransformFinalBlock(_valueByte, 0, _valueByte.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } }           //AES解密      public static string AesDecrypt(string value, string key, string iv = "") { if (string.IsNullOrEmpty(value)) return string.Empty; if (key == null) throw new Exception("未将对象引用设置到对象的实例。"); if (key.Length < 16) throw new Exception("指定的密钥长度不能少于16位。"); if (key.Length > 32) throw new Exception("指定的密钥长度不能多于32位。"); if (key.Length != 16 && key.Length != 24 && key.Length != 32) throw new Exception("指定的密钥长度不明确。"); if (!string.IsNullOrEmpty(iv)) { if (iv.Length < 16) throw new Exception("指定的向量长度不能少于16位。"); } var _keyByte = Encoding.UTF8.GetBytes(key); var _valueByte = Convert.FromBase64String(value); using (var aes = new RijndaelManaged()) { aes.IV = !string.IsNullOrEmpty(iv) ? Encoding.UTF8.GetBytes(iv) : Encoding.UTF8.GetBytes(key.Substring(0, 16)); aes.Key = _keyByte; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; var cryptoTransform = aes.CreateDecryptor(); var resultArray = cryptoTransform.TransformFinalBlock(_valueByte, 0, _valueByte.Length); return Encoding.UTF8.GetString(resultArray); } }

 

  第一次发贴,不喜勿喷!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3