C#国密SM2加密算法实现

  • Post author:
  • Post category:其他

最近在做数据上报,上报数据需要使用国密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);
        }
    }
}

运行效果

在这里插入图片描述


版权声明:本文为Qcg0223原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。