AES
Posted ives
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AES相关的知识,希望对你有一定的参考价值。
public static class AESEncryptionUtility
{
public static string Encrypt(string data, string key, string iv = null, CipherMode mode= CipherMode.CBC, PaddingMode paddingMode= PaddingMode.PKCS7)
{
byte[] bytes = Encoding.UTF8.GetBytes(data);
RijndaelManaged rijndaelManaged = new RijndaelManaged
{
Key = Convert.FromBase64String(key),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
if (!string.IsNullOrEmpty(iv))
{
rijndaelManaged.IV = Encoding.UTF8.GetBytes(iv);
}
rijndaelManaged.Mode = mode;
rijndaelManaged.Padding = paddingMode;
ICryptoTransform cryptoTransform = rijndaelManaged.CreateEncryptor();
byte[] array = cryptoTransform.TransformFinalBlock(bytes, 0, bytes.Length);
var result = Convert.ToBase64String(array, 0, array.Length);
return result;
}
public static string Decrypt(string data, string key, string iv=null, CipherMode mode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7)
{
byte[] array = Convert.FromBase64String(data);
RijndaelManaged rijndaelManaged = new RijndaelManaged
{
Key = Convert.FromBase64String(key),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
if (!string.IsNullOrEmpty(iv))
{
rijndaelManaged.IV = Encoding.UTF8.GetBytes(iv);
}
rijndaelManaged.Mode = mode;
rijndaelManaged.Padding = paddingMode;
ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor();
byte[] bytes = cryptoTransform.TransformFinalBlock(array, 0, array.Length);
var result = Encoding.UTF8.GetString(bytes);
return result;
}
public static string AesGenKey(int size,CipherMode mode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7)
{
RijndaelManaged rijndaelManaged = new RijndaelManaged
{
KeySize = size,
Mode = mode,
Padding = paddingMode
};
rijndaelManaged.GenerateKey();
return Convert.ToBase64String(rijndaelManaged.Key);
}
}
使用方式
[TestMethod]
public void AES()
{
var key=AESEncryptionUtility.AesGenKey(128);
var input = "HelloWorld1";
var secret = AESEncryptionUtility.Encrypt(input, key, "FFFFF09839694AC6");
Console.WriteLine(secret);
}
[TestMethod]
public void DeAES()
{
var key = AESEncryptionUtility.AesGenKey(128);
var input = "HelloWorld1";
var secret = AESEncryptionUtility.Encrypt(input, key, "FFFFF09839694AC6");
var result = AESEncryptionUtility.Decrypt(secret, key, "FFFFF09839694AC6");
Console.WriteLine(result);
}
以上是关于AES的主要内容,如果未能解决你的问题,请参考以下文章
为什么Crypto ++中的AES代码会产生不同的性能结果?
更新实现代码对称加密与解密剖析:AES,高级加密标准(Advanced Encryption Standard,缩写AES)