C# · 12月 19, 2021

AES加密类

代码(该AES加密解密代码可以和Java互通):

using System; System.IO; System.Security.Cryptography; System.Text;namespace Utils{ /// <summary> /// AES加密解密 </summary> public class AESHelper { #region 加密 <summary> AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法) </summary> <param name=”text”>明文</param> <param name=”key”>密钥<param name=”iv”>向量</param> static string Encrypt(string text,string key,1)”>string iv) { if (text == null || text.Length == 0) { throw (new Exception(“明文不得为空”)); } if (string.IsNullOrWhiteSpace(key)) { 密钥不得为空string.IsNullOrWhiteSpace(iv)) { 向量不得为空if (key.Length < 16) { 密钥长度不能小于16if (iv.Length < 向量长度不能小于16)); } byte[] textBytes = Encoding.UTF8.GetBytes(text); byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] ivBytes = Encoding.UTF8.GetBytes(iv); byte[] salt =byte[] encryptedBytes; RijndaelManaged rijndaelManaged = new RijndaelManaged(); ICryptoTransform transform = null; try { rijndaelManaged.Mode = CipherMode.CBC; rijndaelManaged.Padding = PaddingMode.PKCS7; rijndaelManaged.KeySize = 128; rijndaelManaged.BlockSize = ; rijndaelManaged.Key = keyBytes; rijndaelManaged.IV = ivBytes; transform = rijndaelManaged.CreateEncryptor(); encryptedBytes = transform.TransformFinalBlock(textBytes,0,textBytes.Length); } catch (Exception ex) { throw ex; } finally { rijndaelManaged.Clear(); rijndaelManaged.Dispose(); if (transform != ) transform.Dispose(); } return Convert.ToBase64String(encryptedBytes); } #endregion #region 解密 AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法) <param name=”encryptedString”>密文string Decrypt(string encryptedString,1)”>if (encryptedString == null || encryptedString.Length == 密文不得为空[] decryptedBytes; byte[] encryptedBytes = Convert.FromBase64String(encryptedString); RijndaelManaged rijndaelManaged = rijndaelManaged.CreateDecryptor(); decryptedBytes = transform.TransformFinalBlock(encryptedBytes,encryptedBytes.Length); } Encoding.UTF8.GetString(decryptedBytes); } #endregion }}View Code