C# 使用BouncyCastle进行AEAD_AES_256_GCM加解密

国家实名认证使用到的加密

C# 使用BouncyCastle进行AEAD_AES_256_GCM 加密

         /// <summary>
        /// 使用BouncyCastle进行AEAD_AES_256_GCM 加密
        /// </summary>
        /// <param name="key">key32位字符</param>
        /// <param name="nonce">随机串12位</param>
        /// <param name="plainData">明文</param>
        /// <param name="associatedData">附加数据可能null</param>
        /// <returns></returns>
        public static string AesGcmEncryptByBouncyCastleBy(string key, string nonce, string plainData, string associatedData)
        {
            var associatedBytes = associatedData == null ? null : Encoding.UTF8.GetBytes(associatedData);
            byte[] byteData = StrToHexByte(key);
            byte[] values = GetRandomBytes(12);
            var gcmBlockCipher = new GcmBlockCipher(new AesEngine());
            var parameters = new AeadParameters(
                new KeyParameter(byteData),
                128, //128 = 16 * 8 => (tag size * 8)
                Encoding.UTF8.GetBytes(nonce),
                associatedBytes);

            gcmBlockCipher.Init(true, parameters);

            var data = Encoding.UTF8.GetBytes(plainData);
            var cipherData = new byte[gcmBlockCipher.GetOutputSize(data.Length)];

            var length = gcmBlockCipher.ProcessBytes(data, 0, data.Length, cipherData, 0);
            gcmBlockCipher.DoFinal(cipherData, length);
            var resutl= Concat(values, cipherData);
            return Convert.ToBase64String(resutl);
        }

使用BouncyCastle进行AEAD_AES_256_GCM解密

       /// <summary>
        /// aes-cgm解密
        /// </summary>
        /// <param name="key"></param>
        /// <param name="nonce"></param>
        /// <param name="cipherData"></param>
        /// <param name="associatedData"></param>
        /// <returns></returns>
        public static string AesGcmDecryptByBouncyCastle(string key, string nonce, string cipherData, string associatedData)
        {
            var associatedBytes = associatedData == null ? null : Encoding.UTF8.GetBytes(associatedData);

            byte[] byteData = StrToHexByte(key);

            var gcmBlockCipher = new GcmBlockCipher(new AesEngine());
            byte[] values = GetRandomBytes(12);
            var parameters = new AeadParameters(
            new KeyParameter(byteData),
            128,  //128 = 16 * 8 => (tag size * 8)
            Encoding.UTF8.GetBytes(nonce),
            associatedBytes);
            gcmBlockCipher.Init(false, parameters);

            var data = Convert.FromBase64String(cipherData);
            //去掉前面12个字符
            var result = Sub(12, data);
            var plaintext = new byte[gcmBlockCipher.GetOutputSize(result.Length)];

            var length = gcmBlockCipher.ProcessBytes(result, 0, result.Length, plaintext, 0);

            gcmBlockCipher.DoFinal(plaintext, length);
            return Encoding.UTF8.GetString(plaintext);
        }

公用底层方法

        
       public static byte[] StrToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
	   //合并字节
       public static byte[] Concat(byte[] a, byte[] b)
        {
            byte[] output = new byte[a.Length + b.Length];

            for (int i = 0; i < a.Length; i++)
            {
                output[i] = a[i];
            }

            for (int j = 0; j < b.Length; j++)
            {
                output[a.Length + j] = b[j];
            }

            return output;
        }
		 //去掉前面12个字符
		 public static byte[] Sub(int subNum, byte[] b)
        {
            byte[] output = new byte[b.Length-subNum];

            for (int i = 0; i < b.Length; i++)
            {
                if (i < subNum)
                {
                    continue;
                }
                output[i-12] = b[i];
            }
            return output;
        }
	
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用Bouncy Castle库进行SM4加解密的示例程序: ```java import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.engines.SM4Engine; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.encoders.Hex; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; public class SM4Example { public static void main(String[] args) { // 待加密的数据 String plaintext = "Hello, world!"; byte[] plaintextBytes = plaintext.getBytes(StandardCharsets.UTF_8); // 生成随机密钥和IV byte[] key = new byte[16]; byte[] iv = new byte[16]; SecureRandom random = new SecureRandom(); random.nextBytes(key); random.nextBytes(iv); // 初始化SM4算法引擎和CBC模式 BlockCipher engine = new SM4Engine(); CBCBlockCipher cipher = new CBCBlockCipher(engine); // 将密钥和IV转换为参数 KeyParameter keyParam = new KeyParameter(key); ParametersWithIV params = new ParametersWithIV(keyParam, iv); // 加密数据 cipher.init(true, params); byte[] ciphertextBytes = new byte[cipher.getOutputSize(plaintextBytes.length)]; int len = cipher.processBytes(plaintextBytes, 0, plaintextBytes.length, ciphertextBytes, 0); try { cipher.doFinal(ciphertextBytes, len); } catch (Exception e) { e.printStackTrace(); } String ciphertext = Hex.toHexString(ciphertextBytes); System.out.println("加密后的数据:" + ciphertext); // 解密数据 cipher.init(false, params); byte[] decryptedBytes = new byte[cipher.getOutputSize(ciphertextBytes.length)]; len = cipher.processBytes(ciphertextBytes, 0, ciphertextBytes.length, decryptedBytes, 0); try { cipher.doFinal(decryptedBytes, len); } catch (Exception e) { e.printStackTrace(); } String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8); System.out.println("解密后的数据:" + decryptedText); } } ``` 该示例程序使用Bouncy Castle库的SM4引擎和CBC模式对数据进行加解密,并将结果输出到控制台。需要注意的是,SM4算法使用128位密钥和128位IV,因此在示例程序中生成了随机的16字节密钥和IV。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值