C# SM2算法 加密,解密,签名,验签
最近时间在整SM2算法,在网上看到不少代码,基本都是使用BouncyCastle库,现在这个版本算比较好的拿来分享给大家。
首先引入包 Portable.BouncyCastle

完整代码见Gitee:https://gitee.com/Karl_Albright/CryptoHelper/blob/master/src/CryptoHelper/SM2CryptoUtil.cs
public class SM2CryptoUtil
{
public SM2CryptoUtil(byte[] pubkey, byte[] privkey, Mode mode)
{
this.pubkey = pubkey;
this.privkey = privkey;
this.mode = mode;
}
public SM2CryptoUtil(string pubkey, string privkey, Mode mode = Mode.C1C2C3, bool isPkcs8 = false)
{
if (!isPkcs8)
{
if (pubkey != null) this.pubkey = Decode(pubkey);
if (privkey != null) this.privkey = Decode(privkey);
}
else
{
if (pubkey != null) this.pubkey = ((ECPublicKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(pubkey))).Q.GetEncoded();
if (privkey != null) this.privkey = ((ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privkey))).D.ToByteArray();
}
this.mode = mode;
}
byte[] pubkey;
byte[] privkey;
Mode mode;
ICipherParameters _privateKeyParameters;
ICipherParameters PrivateKeyParameters
{
get
{
var r = _privateKeyParameters;
if (r == null) r = _privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, privkey), new ECDomainParameters(GMNamedCurves.GetByName("SM2P256V1")));
return r;
}
}
ICipherParameters _publicKeyParameters;
ICipherParameters PublicKeyParameters
{
get
{
var r = _publicKeyParameters;
if (r == null)
{
var x9ec = GMNamedCurves.GetByName("SM2P256V1");
r = _publicKeyParameters = new ECPublicKeyParameters(x9ec.Curve.DecodePoint(pubkey), new ECDomainParameters(x9ec));
}
return r;
}
} public static void GenerateKeyHex(out string pubkey, out string privkey)
{
GenerateKey(out var a, out var b);
pubkey = Hex.ToHexString(a);
privkey = Hex.ToHexString(b);
}
public static void GenerateKey(out byte[] pubkey, out byte[] privkey)
{
var g = new ECKeyPairGenerator();
g.Init(new ECKeyGenerationParameters(new ECDomainParameters(GMNamedCurves.GetByName("SM2P256V1")), new SecureRandom()));
var k = g.GenerateKeyPair();
pubkey = ((ECPublicKeyParameters)k.Public).Q.GetEncoded(false);
privkey = ((ECPrivateKeyParameters)k.Private).D.ToByteArray();
} public byte[] Decrypt(byte[] data)
{
if (mode == Mode.C1C3C2) data = C132ToC123(data);
var sm2 = new SM2Engine(new SM3Digest());
sm2.Init(false, this.PrivateKeyParameters);
return sm2.ProcessBlock(data, 0, data.Length);
}
public byte[] Encrypt(byte[] data)
{
var sm2 = new SM2Engine(new SM3Digest());
sm2.Init(true, new ParametersWithRandom(PublicKeyParameters));
data = sm2.ProcessBlock(data, 0, data.Length);
if (mode == Mode.C1C3C2) data = C123ToC132(data);
return data;
}
public byte[] Sign(byte[] msg, byte[] id = null)
{
var sm2 = new SM2Signer(new SM3Digest());
ICipherParameters cp;
if (id != null) cp = new ParametersWithID(new ParametersWithRandom(PrivateKeyParameters), id);
else cp = new ParametersWithRandom(PrivateKeyParameters);
sm2.Init(true, cp);
sm2.BlockUpdate(msg, 0, msg.Length);
return sm2.GenerateSignature();
}
public bool VerifySign(byte[] msg, byte[] signature, byte[] id = null)
{
var sm2 = new SM2Signer(new SM3Digest());
ICipherParameters cp;
if (id != null) cp = new ParametersWithID(PublicKeyParameters, id);
else cp = PublicKeyParameters;
sm2.Init(false, cp);
sm2.BlockUpdate(msg, 0, msg.Length);
return sm2.VerifySignature(signature);
}
static byte[] C123ToC132(byte[] c1c2c3)
{
var gn = GMNamedCurves.GetByName("SM2P256V1");
int c1Len = (gn.Curve.FieldSize + 7) / 8 * 2 + 1;
int c3Len = 32;
byte[] result = new byte[c1c2c3.Length];
Array.Copy(c1c2c3, 0, result, 0, c1Len); //c1
Array.Copy(c1c2c3, c1c2c3.Length - c3Len, result, c1Len, c3Len); //c3
Array.Copy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.Length - c1Len - c3Len); //c2
return result;
}
static byte[] C132ToC123(byte[] c1c3c2)
{
var gn = GMNamedCurves.GetByName("SM2P256V1");
int c1Len = (gn.Curve.FieldSize + 7) / 8 * 2 + 1;
int c3Len = 32;
byte[] result = new byte[c1c3c2.Length];
Array.Copy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
Array.Copy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.Length - c1Len - c3Len); //c2
Array.Copy(c1c3c2, c1Len, result, c1c3c2.Length - c3Len, c3Len); //c3
return result;
}
static byte[] Decode(string key)
{
return Regex.IsMatch(key, "^[0-9a-f]+$", RegexOptions.IgnoreCase) ? Hex.Decode(key) : Convert.FromBase64String(key);
}
public enum Mode
{
C1C2C3, C1C3C2
}
}
踩坑记录:
1. 网上有不少教程也是使用 Portable.BouncyCastle库类,但SM2算法写了很多代码(我也没看懂,估计是自己计算椭圆曲线),但加密起来通过在线工具 有时可以解密有时又不行。估计也是使用旧版本。
2. 由于客户提供的密钥是pkcs8,我使用的在线工具是 https://aks.jd.com/tools/sec/。其他的在线工具不一定很解密。估计也是使用旧版本。
3. 客户签名后在我这里验签一直不通过,后来客户把 org.bouncycastle的jar包从1.58升级到1.62才解决这个问题,他们自己也说1.58的jar包签名的用1.62的jar包是验签不通过的。建议大家使用时都使用最新版本。
4. 签名和验签时 id 如果不传会使用默认值 1234567812345678,下面代码里面前两种写法是等效的
signTool.VerifySign(dataBytes, signBytes); //true
signTool.VerifySign(dataBytes, signBytes, Encoding.ASCII.GetBytes("1234567812345678")); // true
signTool.VerifySign(dataBytes, signBytes, new byte[] { }); // false

5. SM2签名就是 SM3WithSM2签名。
C# SM2算法 加密,解密,签名,验签的更多相关文章
- RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密
原文:RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密 C#在using System.Security.Cryptograph ...
- C# RSACryptoServiceProvider加密解密签名验签和DESCryptoServic
C#在using System.Security.Cryptography下有 DESCryptoServiceProvider RSACryptoServiceProvider DESCryptoS ...
- js rsa sign使用笔记(加密,解密,签名,验签)
你将会收获: js如何加密, 解密 js如何签名, 验签 js和Java交互如何相互解密, 验签(重点) 通过谷歌, 发现jsrsasign库使用者较多. 查看api发现这个库功能很健全. 本文使用方 ...
- Java RSA 加密 解密 签名 验签
原文:http://gaofulai1988.iteye.com/blog/2262802 import java.io.FileInputStream; import java.io.FileOut ...
- 支付接口中常用的加密解密以及验签rsa,md5,sha
一.常用加密类型分类 1.对称加密:采用单钥对信息进行加密和解密,即同一个秘钥既可以对信息进行加密,也可以进行解密.此类型称之为对称加密.特点速度快,常用于对大量数据信息或文件加密时使用.常用例子:D ...
- .NET Core 使用RSA算法 加密/解密/签名/验证签名
前言 前不久移植了支付宝官方的SDK,以适用ASP.NET Core使用支付宝支付,但是最近有好几位用户反应在Linux下使用会出错,调试发现是RSA加密的错误,下面具体讲一讲. RSA在.NET C ...
- C# Pkcs8 1024位 加密 解密 签名 解签
部分代码来至 https://www.cnblogs.com/dj258/p/6049786.html using System; using System.Collections.Generic; ...
- RSA密钥生成、加密解密、签名验签
RSA 非对称加密公钥加密,私钥解密 私钥签名,公钥验签 下面是生成随机密钥对: //随机生成密钥对 KeyPairGenerator keyPairGen = null; try { keyPair ...
- [Python3] RSA的加解密和签名/验签实现 -- 使用pycrytodome
Crypto 包介绍: pycrypto,pycrytodome 和 crypto 是一个东西,crypto 在 python 上面的名字是 pycrypto 它是一个第三方库,但是已经停止更新,所以 ...
- RSA加密解密与加签验签
RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.1987年7月首次在美国公布 ...
随机推荐
- 举例useContext性能低下的样例,同时推荐用什么方法改进
在React中,useContext 是一种非常方便的全局状态管理工具,它可以让我们在组件之间共享状态,而不需要通过层层传递 props.然而,当我们在一个大型的 React 应用中过度使用 useC ...
- vue-axios设置公共的请求ip
1.安装axios,网上找方法 2.src->network->request.js并复制: import axios from 'axios' export function reque ...
- Spire.Doc 生成长图
按模板生成内容,转换成长图保存: Document doc = new Document("A_BizRpt.docx"); ....... Image[] imgs = doc. ...
- Pytorch入门—Tensors张量的学习
Tensors张量的学习 张量是一种特殊的数据结构,与数组和矩阵非常相似.在PyTorch中,我们使用张量来编码模型的输入和输出,以及模型的参数. 张量类似于NumPy的ndarrays,只是张量可以 ...
- 【OpenVINO™】使用OpenVINO™ C# API 部署 YOLO-World实现实时开放词汇对象检测
YOLO-World是一个融合了实时目标检测与增强现实(AR)技术的创新平台,旨在将现实世界与数字世界无缝对接.该平台以YOLO(You Only Look Once)算法为核心,实现了对视频中物体的 ...
- Protues的串口工具Virtual Terminal
用Protues来验证ARM的串口发送,有两种办法,一种是用Protues的串口工具VirtualTerminal 第二种是用串口助手(此种方法,需要下载并安装虚拟串口软件,然后用虚拟串口连接虚拟硬件 ...
- 若依报错:登录状态已过期,您可以继续留在该页面,或者重新登录;When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header.
报错界面 后台报错 java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot c ...
- 4G EPS 中建立 UE 与 eNB 之间的 RRC 连接
目录 文章目录 目录 前文列表 RRC 连接 Radio Bearer SRB UE 与 eNB 建立 RRC 连接的流程 前文列表 <4G EPS 中的小区搜索> <4G EPS ...
- MySQL面试必备三之事务
本文首发于公众号:Hunter后端 原文链接:MySQL面试必备三之事务 这一篇笔记介绍一下 MySQL 的事务,面试中常被问到关于事务的几个问题如下: 事务是什么 为什么需要事务,事务有什么作用 事 ...
- springboot使controller异步调用
调用controller方法,遇到操作时间很长的情况下,不希望前端一直等待操作,而希望前端立马接收到操作启动的反馈,而真正的操作在后端执行,需要用到异步调用的方法.实现步骤如下: 一.配置异步支持: ...