C# 实现AES GCM加解密

// 使用的包
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);
}
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值