C#国密SM2加密算法实现

最近在做数据上报,上报数据需要使用国密SM2加密算法加密后上传,以前没接触过过这个东东,所以做个简单记录,平台提供给加密的公钥,让后我们根据公钥将数据加密后,提交给接口,以保证数据安全传输。

实现代码

using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HSSB
{
    /******************************************************** 
      * 项目名称: Program.cs
      * 命名空间 : HSSB
      * 类 名 称 : Program
      * 作   者  : RoyeeCai
      * 邮   箱  : caimh0223@163.com
      * 概   述  : 
      * 创建时间 : 2022-04-20 12:23:40
      * 更新时间 : 2022-04-20 12:23:40
      * CLR版本  : 4.0.30319.42000
      * ******************************************************
      * Copyright@RoyeeCai 2022 .All rights reserved.
      * ******************************************************
      */
    class Program
    {
        static void Main(string[] args)
        {
            // 公钥  平台提供
            String publicKey = "3059301306072a8648ce3d020106082a811ccf5501822d03420004aaa1dae5c13eacf0bf98a3570070101f1e0ce7be2bc000a702595a136ac18e0c109119314897b51d81e29a746d0913a7f364b5853dfcb901eff6826401981791";
            //待加密字符串
            String val = "{\"userName\":\"王小宝\",\"age\":\"10\"}";

            //String s1 = Util4Hex.bytesToHexString(EncryptPublic(publicKey, Encoding.Default.GetBytes(val)));
            String s = Encoding.UTF8.GetString(Hex.Encode(EncryptPublic(publicKey, Encoding.UTF8.GetBytes(val))));
            //Console.WriteLine(s1);
            Console.WriteLine("=========以下为加密后的字符串=========");
            Console.WriteLine(s);  
            Console.ReadKey();
        }

        /// <summary>
        /// 生成SM2加密字符串
        /// </summary>
        /// <param name="pubKey"></param>
        /// <param name="srcData"></param>
        /// <returns></returns>
        public static byte[] EncryptPublic(String pubKey, byte[] srcData)
        {
            //byte[] publicKeyByte = Util4Hex.hexStringToBytes(pubKey);
            byte[] publicKeyByte = hexStringToBytes(pubKey);
            ECPublicKeyParameters ECPPublicKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(publicKeyByte);
            SM2Engine engine = new SM2Engine();
            ParametersWithRandom pwr = new ParametersWithRandom(ECPPublicKey, new SecureRandom());
            engine.Init(true, pwr);
            return engine.ProcessBlock(srcData, 0, srcData.Length);
        }

        /**
         * Convert hex string to byte[]
         * 
         * @param hexString the hex string
         * @return byte[]
         */
        public static byte[] hexStringToBytes(String hexString)
        {
            if (hexString == null || hexString.Equals(""))
            {
                return null;
            }
            hexString = hexString.ToUpper();
            int length = hexString.Length / 2;
            char[] hexChars = hexString.ToCharArray();
            byte[] d = new byte[length];
            for (int i = 0; i < length; i++)
            {
                int pos = i * 2;
                d[i] = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
            }
            return d;
        }

        /**
         * Convert char to byte
         * 
         * @param c char
         * @return byte
         */
        private static byte charToByte(char c)
        {
            return (byte)"0123456789ABCDEF".IndexOf(c);
        }
    }
}

运行效果

在这里插入图片描述

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值