标签:null base public oba block gets nsf dea ati
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);
}
标签:null base public oba block gets nsf dea ati
原文地址:https://www.cnblogs.com/ives/p/12067041.html