最近时间在整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算法 加密,解密,签名,验签的更多相关文章

  1. RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密

    原文:RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密 C#在using System.Security.Cryptograph ...

  2. C# RSACryptoServiceProvider加密解密签名验签和DESCryptoServic

    C#在using System.Security.Cryptography下有 DESCryptoServiceProvider RSACryptoServiceProvider DESCryptoS ...

  3. js rsa sign使用笔记(加密,解密,签名,验签)

    你将会收获: js如何加密, 解密 js如何签名, 验签 js和Java交互如何相互解密, 验签(重点) 通过谷歌, 发现jsrsasign库使用者较多. 查看api发现这个库功能很健全. 本文使用方 ...

  4. Java RSA 加密 解密 签名 验签

    原文:http://gaofulai1988.iteye.com/blog/2262802 import java.io.FileInputStream; import java.io.FileOut ...

  5. 支付接口中常用的加密解密以及验签rsa,md5,sha

    一.常用加密类型分类 1.对称加密:采用单钥对信息进行加密和解密,即同一个秘钥既可以对信息进行加密,也可以进行解密.此类型称之为对称加密.特点速度快,常用于对大量数据信息或文件加密时使用.常用例子:D ...

  6. .NET Core 使用RSA算法 加密/解密/签名/验证签名

    前言 前不久移植了支付宝官方的SDK,以适用ASP.NET Core使用支付宝支付,但是最近有好几位用户反应在Linux下使用会出错,调试发现是RSA加密的错误,下面具体讲一讲. RSA在.NET C ...

  7. C# Pkcs8 1024位 加密 解密 签名 解签

    部分代码来至 https://www.cnblogs.com/dj258/p/6049786.html using System; using System.Collections.Generic; ...

  8. RSA密钥生成、加密解密、签名验签

    RSA 非对称加密公钥加密,私钥解密 私钥签名,公钥验签 下面是生成随机密钥对: //随机生成密钥对 KeyPairGenerator keyPairGen = null; try { keyPair ...

  9. [Python3] RSA的加解密和签名/验签实现 -- 使用pycrytodome

    Crypto 包介绍: pycrypto,pycrytodome 和 crypto 是一个东西,crypto 在 python 上面的名字是 pycrypto 它是一个第三方库,但是已经停止更新,所以 ...

  10. RSA加密解密与加签验签

    RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.1987年7月首次在美国公布 ...

随机推荐

  1. React项目中报错:Parsing error: The keyword 'import' is reservedeslint

    记得更改完配置后,要重启编辑器(如:VSCode)!!! 记得更改完配置后,要重启编辑器(如:VSCode)!!! 记得更改完配置后,要重启编辑器(如:VSCode)!!! 这个错误通常发生在你尝试在 ...

  2. golang 常用操作

    golang 获取切片 slice 第一个 最后一个 元素 复合数据类型切片通常用作Go中索引数据的口语结构. 该类型[]intSlice是具有类型为integer的元素的切片. len函数用于获取切 ...

  3. 关于Java Chassis 3的契约优先(API First)开发

    本文分享自华为云社区<Java Chassis 3技术解密:契约优先(API First)开发>,作者: liubao68. 契约优先(API First)开发是指应用程序开发过程中,将A ...

  4. linux文件查找工具详解

    linux文件查找详解 目录 linux文件查找详解 1.linux文件查找工具 1.1 find命令详解 1.1.1 根据文件名查找 1.1.2 根据属主属组查找 1.1.3 根据文件类型查找 1. ...

  5. make编译报错:fatal error: filesystem: 没有那个文件或目录 #include <filesystem>

    报错: fatal error: filesystem: 没有那个文件或目录 #include(filesystem) 解决方法一: 修改头文件 #include <experimental/f ...

  6. java如何将JSONObject转成实体对象

    import com.google.gson.Gson; import org.json.JSONObject; // ... JSONObject json = new JSONObject(&qu ...

  7. uniapp去除button的边框

    button { border: none !important; } button::after { border: none !important; }

  8. VRRP 虚拟路由器冗余协议

    目录 文章目录 目录 为什么要使用 VRRP 技术? VRRP VRRP 的概念 VRRP 的工作原理 VRRP 的状态机 VRRP 的工作过程 VRRP 的选举机制 VRRP 的报文格式 VRRP ...

  9. 国产系统UOS安装体验

    原文链接 https://www.giantliu.cn/2020/09/04/200904InstallUOS/ UOS简介 统信桌面操作系统(Uniontech OS)个人正式版是统信软件基于Li ...

  10. PageOffice 6 版本最简单的打开保存文件

    在OA办公.文档流转等各个Web系统中,实现最简单的打开编辑保存文件功能,调用PageOffice只需要几行代码就可以完成. 后端代码 在后端编写代码调用webOpen方法打开文件之前给SaveFil ...