C#国密SM2加密算法实现

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

实现代码

  • 该加密算法需要引入【BouncyCastle 】https://www.bouncycastle.org/文件。
    C#国密SM2加密算法实现_第1张图片
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
      * 邮   箱  : [email protected]
      * 概   述  : 
      * 创建时间 : 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();
        }

        /// 
        /// 生成SM2加密字符串
        /// 
        /// 
        /// 
        /// 
        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);
        }
    }
}

运行效果

C#国密SM2加密算法实现_第2张图片

你可能感兴趣的:(C#.NET,个人笔记,SM2,C#,算法)