完整代码
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Script.Common.Utils
{
public class AESUtils
{
public static string Encrypt(string content, string key)
{
byte[] keyBytes = UTF8Encoding.UTF8.GetBytes(key);
RijndaelManaged rm = new RijndaelManaged();
rm.Key = keyBytes;
rm.Mode = CipherMode.ECB;
rm.Padding = PaddingMode.PKCS7;
ICryptoTransform ict = rm.CreateEncryptor();
byte[] contentBytes = UTF8Encoding.UTF8.GetBytes(content);
byte[] resultBytes = ict.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
return ConvertByteToHexString(resultBytes);
}
public static string Decrypt(string content, string key)
{
byte[] keyBytes = UTF8Encoding.UTF8.GetBytes(key);
RijndaelManaged rm = new RijndaelManaged();
rm.Key = keyBytes;
rm.Mode = CipherMode.ECB;
rm.Padding = PaddingMode.PKCS7;
ICryptoTransform ict = rm.CreateDecryptor();
byte[] contentBytes = ConvertHexStringToBytes(content);
byte[] resultBytes = ict.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
return UTF8Encoding.UTF8.GetString(resultBytes);
}
public static string ConvertByteToHexString(byte[] bytes)
{
StringBuilder ret = new StringBuilder();
foreach (byte b in bytes)
{
ret.AppendFormat("{0:x2}", b);
}
var hex = ret.ToString();
return hex;
}
public static byte[] ConvertHexStringToBytes(string hexString)
{
hexString = hexString.Replace(" ", "");
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
{
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return returnBytes;
}
}
}