using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
public class AES
{
public static String Key = "www.02405.com";
/// <summary>
/// AES 加密
/// </summary>
/// <param name="str">明文(待加密)</param>
/// <param name="key">密文</param>
/// <returns></returns>
public static string AesEncrypt(string str)
{
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, 0, toEncryptArray.Length);
String HexString = String.Join("", resultArray.Select(item => item.ToString("X2"))).ToUpper();
return HexString;
}
/// <summary>
/// AES 解密
/// </summary>
/// <param name="str">明文(待解密)</param>
/// <param name="key">密文</param>
/// <returns></returns>
public static string AesDecrypt(string str)
{
Byte[] toEncryptArray = parseHexStrToByte(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, 0, toEncryptArray.Length);
return Encoding.UTF8.GetString(resultArray);
}
/// <summary>
/// 字符串转字节
/// </summary>
/// <param name="hexStr"></param>
/// <returns></returns>
public static byte[] parseHexStrToByte(String hexStr)
{
if (hexStr.Length < 1)
return null;
byte[] result = new byte[hexStr.Length / 2];
for (int i = 0; i < hexStr.Length / 2; i++)
{
String Char = hexStr.Substring(i * 2, 2);
result[i] = Convert.ToByte(Char, 16);
}
return result;
}
}
零五网 - 为热爱技术的人而生!
C# AES 加解密类
0 Previous ArticleC# 软件注册机制实现指南(基于rsa加密算法)
Next Article .net 文件监听类