/// <summary>
/// 有密码的AES加密
/// </summary>
/// <param name="text">加密字符</param>
/// <returns></returns>
public static string AESEncrypt(string text)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] keyBytes = new byte[16];
rijndaelCipher.Key = GetKey();// keyBytes;
rijndaelCipher.IV = GetIv();
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(text);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
}
/// <summary>
/// 获取密钥
/// </summary>
/// <returns></returns>
public static byte[] GetKey()
{
byte[] arrChar = new byte[]{0x21, 0x24, 0x16, 0x58, 0x30, 0x5B, 0xCD,
0x42, 0x93, 0xAB, 0x56, 0xDE, 0xAC, 0x26, 0xEF, 0xCD };
return arrChar;
}
/// <summary>
/// 获取默认密钥向量
/// </summary>
/// <returns></returns>
public static byte[] GetIv()
{
byte[] arrChar = new byte[]{0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD,
0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0x31, 0x78 };
return arrChar;
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string AESDecrypt(string text, byte[] key, byte[] iv)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] encryptedData = Convert.FromBase64String(text);
rijndaelCipher.Key = key;
rijndaelCipher.IV = iv;
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}
C#数据安全加密之AES
最新推荐文章于 2023-02-06 09:00:00 发布