C# AES-128-CBC 加密
一、加密
/// <summary>
/// 加密
/// </summary>
public static string AesEncrypt(string toEncrypt)
{
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key);//注意编码格式(utf8编码 UTF8Encoding)
byte[] ivArray = UTF8Encoding.UTF8.GetBytes(Iv);
RijndaelManaged rDel = new RijndaelManaged();
rDel.KeySize = 128;
rDel.BlockSize = 128;
rDel.Key = keyArray;
rDel.IV = ivArray;
rDel.Mode = CipherMode.CBC;
ICryptoTransform cTransform = rDel.CreateEncryptor();//加密
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
二、解密
/// <summary>
/// 解密
/// </summary>
public static string AesDecrypt(string toDecrypt)
{
string key32 = Key.PadRight(16);
byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key);//注意编码格式(utf8编码 UTF8Encoding)
byte[] ivArray = UTF8Encoding.UTF8.GetBytes(Iv);
RijndaelManaged rDel = new RijndaelManaged();
rDel.KeySize = 128;
rDel.BlockSize = 128;
rDel.Key = keyArray;
rDel.IV = ivArray;
rDel.Mode = CipherMode.CBC;
ICryptoTransform cTransform = rDel.CreateDecryptor();//解密
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return UTF8Encoding.UTF8.GetString(resultArray);
}
三、具体使用
static void Main(string[] args)
{
AESEncoder.Key = "nsmkindi".PadRight(16);string s1 = AESEncoder.AesEncrypt("abcd123哪里");
Console.WriteLine("加密:" + s1);string s2 = AESEncoder.AesDecrypt(s1);
Console.WriteLine("解密:" + s2);Console.ReadKey();
}
四、完结。