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;
            }
        }
    }
}

下载

源码下载

相关推荐
高山我梦口香糖7 分钟前
[react]searchParams转普通对象
开发语言·前端·javascript
信号处理学渣29 分钟前
matlab画图,选择性显示legend标签
开发语言·matlab
红龙创客29 分钟前
某狐畅游24校招-C++开发岗笔试(单选题)
开发语言·c++
jasmine s38 分钟前
Pandas
开发语言·python
biomooc1 小时前
R 语言 | 绘图的文字格式(绘制上标、下标、斜体、文字标注等)
开发语言·r语言
骇客野人1 小时前
【JAVA】JAVA接口公共返回体ResponseData封装
java·开发语言
black^sugar1 小时前
纯前端实现更新检测
开发语言·前端·javascript
404NooFound1 小时前
Python轻量级NoSQL数据库TinyDB
开发语言·python·nosql
用余生去守护2 小时前
python报错系列(16)--pyinstaller ????????
开发语言·python
数据小爬虫@2 小时前
利用Python爬虫快速获取商品历史价格信息
开发语言·爬虫·python