// 使用的包
using NPOI.POIFS.Crypt;
/// <summary>
/// AES GCM 加密
/// </summary>
/// <param name="key">密钥</param>
/// <param name="iv">向量</param>
/// <param name="data">数据</param>
/// <returns></returns>
private static string AesGcmEncryptToBase64(string key, string iv, string data)
{
var keyBytes = Encoding.UTF8.GetBytes(key);
var ivBytes = Encoding.UTF8.GetBytes(iv);
var dataBytes = Encoding.UTF8.GetBytes(data);
SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.GetInstance("AES/GCM/NoPadding");//"算法/模式/补码方式"
cipher.Init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(ivBytes));
byte[] encrypted = cipher.DoFinal(dataBytes);
return Convert.ToBase64String(encrypted);
}
/// <summary>
/// AES GCM 解密
/// </summary>
/// <param name="key">密钥</param>
/// <param name="iv">向量</param>
/// <param name="data">base64数据</param>
private static string AesGcmDecryptTByBase64(string key, string iv, string data)
{
var keyBytes = Encoding.UTF8.GetBytes(key);
var ivBytes = Encoding.UTF8.GetBytes(iv);
var dataBytes = Convert.FromBase64String(data);
SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.GetInstance("AES/GCM/NoPadding");//"算法/模式/补码方式"
cipher.Init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(ivBytes));
byte[] decrypted = cipher.DoFinal(dataBytes);
return Encoding.UTF8.GetString(decrypted);
}
C# 实现AES GCM加解密
于 2022-01-10 15:27:58 首次发布