C# SM2 加签、验签工具

目录

效果

项目

代码

下载


效果

项目

代码

using Org.BouncyCastle.Crypto.Parameters;

using Org.BouncyCastle.Crypto.Signers;

using Org.BouncyCastle.Asn1.GM;

using System;

using System.Text;

using System.Windows.Forms;

using Org.BouncyCastle.Asn1.X9;

using Org.BouncyCastle.Utilities.Encoders;

using Org.BouncyCastle.Math;

using Org.BouncyCastle.Crypto.Generators;

using Org.BouncyCastle.Security;

using System.Linq;

namespace SM2VerifySignTool

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

int toDigit(char ch, int index)

{

int digit = Convert.ToInt32(ch.ToString(), 16);

if (digit == -1)

{

throw new SystemException("Illegal hexadecimal character " + ch + " at index " + index);

}

return digit;

}

string HexToBase64(string hexString)

{

byte[] bytes = Enumerable.Range(0, hexString.Length)

.Where(x => x % 2 == 0)

.Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))

.ToArray();

return Convert.ToBase64String(bytes);

}

byte[] hexStrToByte(String hexStr)

{

if ((null == hexStr) || (hexStr.Length == 0))

{

return null;

}

char[] hexData = hexStr.ToCharArray();

int len = hexData.Length;

if ((len & 0x1) != 0)

{

throw new SystemException("Odd number of characters.");

}

byte[] out1 = new byte[len >> 1];

int i = 0;

for (int j = 0; j < len; i++)

{

int f = toDigit(hexData[j], j) << 4;

j++;

f |= toDigit(hexData[j], j);

j++;

out1[i] = ((byte)(f & 0xFF));

}

return out1;

}

X9ECParameters x9ec = GMNamedCurves.GetByName("SM2P256V1");

/**

*生成

*/

void GenerateKey(out string pubkeyStr, out string prikeyStr)

{

var g = new ECKeyPairGenerator();

g.Init(new ECKeyGenerationParameters(new ECDomainParameters(x9ec), new SecureRandom()));

var k = g.GenerateKeyPair();

byte[] pubkey = ((ECPublicKeyParameters)k.Public).Q.GetEncoded(false);

byte[] privkey = ((ECPrivateKeyParameters)k.Private).D.ToByteArray();

prikeyStr = BitConverter.ToString(privkey).Replace("-", "");

pubkeyStr = BitConverter.ToString(pubkey).Replace("-", "");

}

/**

*加签

*/

string Sign(string prikeyStr, string data)

{

byte[] msg = Encoding.UTF8.GetBytes(data);

byte[] priKey = hexStrToByte(prikeyStr);

SM2Signer sm2Signer = new SM2Signer();

ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, priKey), new ECDomainParameters(x9ec));

sm2Signer.Init(true, privateKeyParameters);

sm2Signer.BlockUpdate(msg, 0, msg.Length);

return Hex.ToHexString(sm2Signer.GenerateSignature());

}

/*

* 验签

*/

bool verifySign(string pubkeyStr, string data, string sign)

{

byte[] signHex = hexStrToByte(sign);

byte[] pubkey = hexStrToByte(pubkeyStr);

byte[] msgByte = Encoding.UTF8.GetBytes(data);

SM2Signer sm2Signer = new SM2Signer();

ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(x9ec.Curve.DecodePoint(pubkey), new ECDomainParameters(x9ec));

sm2Signer.Init(false, publicKeyParameters);

sm2Signer.BlockUpdate(msgByte, 0, msgByte.Length);

return sm2Signer.VerifySignature(signHex);

}

private void btnVerify_Click(object sender, EventArgs e)

{

txtResult.Text = "";

try

{

string pubk = txtPubkey.Text;

string data = txtData.Text;

string sign = txtSign.Text;

bool b = verifySign(pubk, data, sign);

if (b)

{

txtResult.Text = "验证成功";

}

else

{

txtResult.Text = "验证失败";

}

}

catch (Exception ex)

{

txtResult.Text = "验证异常:" + ex.Message;

}

}

/// <summary>

/// Base64字符串转Hex字符串↓

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void button1_Click(object sender, EventArgs e)

{

try

{

byte[] bytes = Convert.FromBase64String(txtBase64.Text); // 将base64字符串转换为byte数组

string hexString = BitConverter.ToString(bytes).Replace("-", ""); // 将byte数组转换为Hex字符串

txtHex.Text = hexString;

}

catch (Exception ex)

{

txtHex.Text = "转换异常:" + ex.Message;

}

}

private void Form1_Load(object sender, EventArgs e)

{

//string pubkeyStr = "";

//string prikeyStr = "";

//GenerateKey(out pubkeyStr, out prikeyStr);

//txtPriKey.Text = prikeyStr;

//txtPubkey.Text = pubkeyStr;

}

private void button2_Click(object sender, EventArgs e)

{

try

{

string prik = txtPriKey.Text;

string data = txtData.Text;

txtSign.Text = Sign(prik, data);

}

catch (Exception ex)

{

txtSign.Text = "加签识别:" + ex.Message;

}

}

private void button3_Click(object sender, EventArgs e)

{

string pubkeyStr = "";

string prikeyStr = "";

GenerateKey(out pubkeyStr, out prikeyStr);

txtPriKey.Text = prikeyStr;

txtPubkey.Text = pubkeyStr;

}

private void button4_Click(object sender, EventArgs e)

{

try

{

string hexString = txtHex.Text;

string base64String = HexToBase64(hexString);

txtBase64.Text = base64String;

}

catch (Exception ex)

{

txtBase64.Text = "转换异常:" + ex.Message;

}

}

private void button5_Click(object sender, EventArgs e)

{

try

{

string originalString = txtStr.Text;

byte[] bytes = System.Text.Encoding.UTF8.GetBytes(originalString);

string base64String = Convert.ToBase64String(bytes);

txtBase64.Text = base64String;

}

catch (Exception ex)

{

txtBase64.Text = "编码异常:" + ex.Message;

}

}

private void button6_Click(object sender, EventArgs e)

{

try

{

string base64String = txtBase64.Text;

byte[] bytes = Convert.FromBase64String(base64String);

string decodedString = Encoding.UTF8.GetString(bytes);

txtStr.Text = decodedString;

}

catch (Exception ex)

{

txtStr.Text = "解码异常:" + ex.Message;

}

}

}

}

using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Asn1.GM;
using System;
using System.Text;
using System.Windows.Forms;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Security;
using System.Linq;

namespace SM2VerifySignTool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int toDigit(char ch, int index)
        {
            int digit = Convert.ToInt32(ch.ToString(), 16);
            if (digit == -1)
            {
                throw new SystemException("Illegal hexadecimal character " + ch + " at index " + index);
            }
            return digit;
        }

        string HexToBase64(string hexString)
        {
            byte[] bytes = Enumerable.Range(0, hexString.Length)
                                     .Where(x => x % 2 == 0)
                                     .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
                                     .ToArray();
            return Convert.ToBase64String(bytes);
        }

        byte[] hexStrToByte(String hexStr)
        {
            if ((null == hexStr) || (hexStr.Length == 0))
            {
                return null;
            }
            char[] hexData = hexStr.ToCharArray();
            int len = hexData.Length;
            if ((len & 0x1) != 0)
            {
                throw new SystemException("Odd number of characters.");
            }
            byte[] out1 = new byte[len >> 1];

            int i = 0;
            for (int j = 0; j < len; i++)
            {
                int f = toDigit(hexData[j], j) << 4;
                j++;
                f |= toDigit(hexData[j], j);
                j++;
                out1[i] = ((byte)(f & 0xFF));
            }
            return out1;
        }

        X9ECParameters x9ec = GMNamedCurves.GetByName("SM2P256V1");


        /**
        *生成
        */
        void GenerateKey(out string pubkeyStr, out string prikeyStr)
        {
            var g = new ECKeyPairGenerator();
            g.Init(new ECKeyGenerationParameters(new ECDomainParameters(x9ec), new SecureRandom()));
            var k = g.GenerateKeyPair();
            byte[] pubkey = ((ECPublicKeyParameters)k.Public).Q.GetEncoded(false);
            byte[] privkey = ((ECPrivateKeyParameters)k.Private).D.ToByteArray();
            prikeyStr = BitConverter.ToString(privkey).Replace("-", "");
            pubkeyStr = BitConverter.ToString(pubkey).Replace("-", "");
        }

        /**
        *加签
        */
        string Sign(string prikeyStr, string data)
        {
            byte[] msg = Encoding.UTF8.GetBytes(data);
            byte[] priKey = hexStrToByte(prikeyStr);
            SM2Signer sm2Signer = new SM2Signer();
            ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, priKey), new ECDomainParameters(x9ec));

            sm2Signer.Init(true, privateKeyParameters);
            sm2Signer.BlockUpdate(msg, 0, msg.Length);
            return Hex.ToHexString(sm2Signer.GenerateSignature());
        }


        /*
        * 验签
        */
        bool verifySign(string pubkeyStr, string data, string sign)
        {
            byte[] signHex = hexStrToByte(sign);
            byte[] pubkey = hexStrToByte(pubkeyStr);
            byte[] msgByte = Encoding.UTF8.GetBytes(data);
            SM2Signer sm2Signer = new SM2Signer();
            ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(x9ec.Curve.DecodePoint(pubkey), new ECDomainParameters(x9ec));
            sm2Signer.Init(false, publicKeyParameters);
            sm2Signer.BlockUpdate(msgByte, 0, msgByte.Length);
            return sm2Signer.VerifySignature(signHex);
        }

        private void btnVerify_Click(object sender, EventArgs e)
        {
            txtResult.Text = "";
            try
            {
                string pubk = txtPubkey.Text;
                string data = txtData.Text;
                string sign = txtSign.Text;
                bool b = verifySign(pubk, data, sign);
                if (b)
                {
                    txtResult.Text = "验证成功";
                }
                else
                {
                    txtResult.Text = "验证失败";
                }
            }
            catch (Exception ex)
            {
                txtResult.Text = "验证异常:" + ex.Message;
            }
        }

        /// <summary>
        /// Base64字符串转Hex字符串↓
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] bytes = Convert.FromBase64String(txtBase64.Text); // 将base64字符串转换为byte数组
                string hexString = BitConverter.ToString(bytes).Replace("-", ""); // 将byte数组转换为Hex字符串
                txtHex.Text = hexString;
            }
            catch (Exception ex)
            {
                txtHex.Text = "转换异常:" + ex.Message;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //string pubkeyStr = "";
            //string prikeyStr = "";
            //GenerateKey(out pubkeyStr, out prikeyStr);
            //txtPriKey.Text = prikeyStr;
            //txtPubkey.Text = pubkeyStr;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string prik = txtPriKey.Text;
                string data = txtData.Text;
                txtSign.Text = Sign(prik, data);
            }
            catch (Exception ex)
            {
                txtSign.Text = "加签识别:" + ex.Message;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string pubkeyStr = "";
            string prikeyStr = "";
            GenerateKey(out pubkeyStr, out prikeyStr);
            txtPriKey.Text = prikeyStr;
            txtPubkey.Text = pubkeyStr;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string hexString = txtHex.Text;
                string base64String = HexToBase64(hexString);
                txtBase64.Text = base64String;
            }
            catch (Exception ex)
            {
                txtBase64.Text = "转换异常:" + ex.Message;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                string originalString = txtStr.Text;
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(originalString);
                string base64String = Convert.ToBase64String(bytes);
                txtBase64.Text = base64String;
            }
            catch (Exception ex)
            {
                txtBase64.Text = "编码异常:" + ex.Message;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                string base64String = txtBase64.Text;
                byte[] bytes = Convert.FromBase64String(base64String);
                string decodedString = Encoding.UTF8.GetString(bytes);
                txtStr.Text = decodedString;
            }
            catch (Exception ex)
            {
                txtStr.Text = "解码异常:" + ex.Message;
            }
        }
    }
}

下载

源码下载

相关推荐
ZwaterZ2 分钟前
vue el-table表格点击某行触发事件&&操作栏点击和row-click冲突问题
前端·vue.js·elementui·c#·vue
生信摆渡8 分钟前
R语言-快速对多个变量取交集
开发语言·数据库·r语言
¥ 多多¥21 分钟前
c++中mystring运算符重载
开发语言·c++·算法
Mr.Pascal27 分钟前
刚学php序列化/反序列化遇到的坑(攻防世界:Web_php_unserialize)
开发语言·安全·web安全·php
小尤笔记38 分钟前
利用Python编写简单登录系统
开发语言·python·数据分析·python基础
秦老师Q41 分钟前
Java基础第九章-Java集合框架(超详细)!!!
java·开发语言
计算机毕设源码qq-383653104143 分钟前
(附项目源码)Java开发语言,215 springboot 大学生爱心互助代购网站,计算机毕设程序开发+文案(LW+PPT)
java·开发语言·spring boot·mysql·课程设计
无尽的大道1 小时前
深入理解 Java 阻塞队列:使用场景、原理与性能优化
java·开发语言·性能优化
建群新人小猿1 小时前
会员等级经验问题
android·开发语言·前端·javascript·php
007php0071 小时前
GoZero 上传文件File到阿里云 OSS 报错及优化方案
服务器·开发语言·数据库·python·阿里云·架构·golang