使用C#帮忙实现国密算法中的SM2椭圆曲线公钥密码算法,谢谢!
SM2算法就是ECC椭圆曲线密码机制,但在签名、密钥交换方面不同于ECDSA、ECDH等国际标准,而是采取了更为安全的机制。另外,SM2推荐了一条256位的曲线作为标准曲线。
SM2标准包括总则,数字签名算法,密钥交换协议,公钥加密算法四个部分,并在每个部分的附录详细说明了实现的相关细节及示例。
最佳解决方案
国密SM2的实现需要借助SM3,SM3杂凑算法的实现参考https://www.hierror.com/demo/article/138054
同样需要引用BouncyCastle.Crypto.dll到项目,一共有三个类:Cipher.cs 、SM2.cs、SM2Helper.cs(主要是如何使用SM2的方法),实现分别如下:
//Chiper.cs
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Demo
{
public class Cipher
{
private int ct = 1;
private ECPoint p2;
private SM3 sm3keybase;
private SM3 sm3c3;
private byte[] key = new byte[32];
private byte keyOff = 0;
public Cipher()
{
}
private void Reset()
{
sm3keybase = new SM3();
sm3c3 = new SM3();
byte[] p;
p = p2.X.ToBigInteger().ToByteArray();
sm3keybase.BlockUpdate(p, 0, p.Length);
sm3c3.BlockUpdate(p, 0, p.Length);
p = p2.Y.ToBigInteger().ToByteArray();
sm3keybase.BlockUpdate(p, 0, p.Length);
ct = 1;
NextKey();
}
private void NextKey()
{
SM3 sm3keycur = new SM3(sm3keybase);
sm3keycur.Update((byte)(ct >> 24 & 0x00ff));
sm3keycur.Update((byte)(ct >> 16 & 0x00ff));
sm3keycur.Update((byte)(ct >> 8 & 0x00ff));
sm3keycur.Update((byte)(ct & 0x00ff));
sm3keycur.DoFinal(key, 0);
keyOff = 0;
ct++;
}
public virtual ECPoint Init_enc(SM2 sm2, ECPoint userKey)
{
BigInteger k = null;
ECPoint c1 = null;
AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.GenerateKeyPair();
ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.Private;
&