.Net已封装好算法,直接调用即可,代码如下:
转载请注明出处:https://www.cnblogs.com/jietian331/p/9707771.html
using System;
using System.Security.Cryptography;
using System.Text; namespace AES
{
class Program
{
static void Main(string[] args)
{
string str = "Hello world";
string key = "12345678876543211234567887654abc";
string result = AesEncrypt(str, key);
Console.WriteLine(result);
Console.WriteLine(AesDecrypt(result, key));
Console.ReadKey();
} /// <summary>
/// AES 加密
/// </summary>
/// <param name="str">明文(待加密)</param>
/// <param name="key">密文</param>
/// <returns></returns>
public static string AesEncrypt(string str, string key)
{
if (string.IsNullOrEmpty(str))
return null;
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); RijndaelManaged rm = new RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
}; ICryptoTransform cTransform = rm.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, , toEncryptArray.Length); return Convert.ToBase64String(resultArray, , resultArray.Length);
}
/// <summary>
/// AES 解密
/// </summary>
/// <param name="str">明文(待解密)</param>
/// <param name="key">密文</param>
/// <returns></returns>
public static string AesDecrypt(string str, string key)
{
if (string.IsNullOrEmpty(str))
return null;
Byte[] toEncryptArray = Convert.FromBase64String(str); RijndaelManaged rm = new RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
}; ICryptoTransform cTransform = rm.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, , toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray);
}
}
}