C#.NET 国密SM3withSM2签名与验签 和JAVA互通
C# 基于.NET FRAMEWORK 4.5
JAVA 基于 JDK1.8
一、要点
1.签名算法:SM3withSM2。
2.签名值byte[] 转字符串时,双方要统一,这里是BASE64。
二、工具类和调用DEMO
C#
引用了BouncyCastle.Crypto类库,在nuget上下载最新即可。
工具类:
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.GM;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.X509;
using System;
using System.Collections.Generic;
using System.IO; namespace CommonUtils
{
/**
* need lib:
* BouncyCastle.Crypto.dll(http://www.bouncycastle.org/csharp/index.html) * 用BC的注意点:
* 这个版本的BC对SM3withSM2的结果为asn1格式的r和s,如果需要直接拼接的r||s需要自己转换。下面rsAsn1ToPlainByteArray、rsPlainByteArrayToAsn1就在干这事。
* 这个版本的BC对SM2的结果为C1||C2||C3,据说为旧标准,新标准为C1||C3||C2,用新标准的需要自己转换。下面(被注释掉的)changeC1C2C3ToC1C3C2、changeC1C3C2ToC1C2C3就在干这事。java版的高版本有加上C1C3C2,csharp版没准以后也会加,但目前还没有,java版的目前可以初始化时“ SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);”。
*
* 按要求国密算法仅允许使用加密机,本demo国密算法仅供学习使用,请不要用于生产用途。
*/
public class GmUtil
{ //private static readonly ILog log = LogManager.GetLogger(typeof(GmUtil)); private static X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
private static ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N); /**
*
* @param msg
* @param userId
* @param privateKey
* @return r||s,直接拼接byte数组的rs
*/
public static byte[] SignSm3WithSm2(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
{
return RsAsn1ToPlainByteArray(SignSm3WithSm2Asn1Rs(msg, userId, privateKey));
} /**
* @param msg
* @param userId
* @param privateKey
* @return rs in <b>asn1 format</b>
*/
public static byte[] SignSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
{
try
{
ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
signer.Init(true, new ParametersWithID(privateKey, userId));
signer.BlockUpdate(msg, 0, msg.Length);
byte[] sig = signer.GenerateSignature();
return sig;
}
catch (Exception e)
{
//log.Error("SignSm3WithSm2Asn1Rs error: " + e.Message, e);
return null;
}
} /**
*
* @param msg
* @param userId
* @param rs r||s,直接拼接byte数组的rs
* @param publicKey
* @return
*/
public static bool VerifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, AsymmetricKeyParameter publicKey)
{
if (rs == null || msg == null || userId == null) return false;
if (rs.Length != RS_LEN * 2) return false;
return VerifySm3WithSm2Asn1Rs(msg, userId, RsPlainByteArrayToAsn1(rs), publicKey);
} /**
*
* @param msg
* @param userId
* @param rs in <b>asn1 format</b>
* @param publicKey
* @return
*/ public static bool VerifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] sign, AsymmetricKeyParameter publicKey)
{
try
{
ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
signer.Init(false, new ParametersWithID(publicKey, userId));
signer.BlockUpdate(msg, 0, msg.Length);
return signer.VerifySignature(sign);
}
catch (Exception e)
{
//log.Error("VerifySm3WithSm2Asn1Rs error: " + e.Message, e);
return false;
}
} /**
* bc加解密使用旧标c1||c2||c3,此方法在加密后调用,将结果转化为c1||c3||c2
* @param c1c2c3
* @return
*/
private static byte[] ChangeC1C2C3ToC1C3C2(byte[] c1c2c3)
{
int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
const int c3Len = 32; //new SM3Digest().getDigestSize();
byte[] result = new byte[c1c2c3.Length];
Buffer.BlockCopy(c1c2c3, 0, result, 0, c1Len); //c1
Buffer.BlockCopy(c1c2c3, c1c2c3.Length - c3Len, result, c1Len, c3Len); //c3
Buffer.BlockCopy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.Length - c1Len - c3Len); //c2
return result;
} /**
* bc加解密使用旧标c1||c3||c2,此方法在解密前调用,将密文转化为c1||c2||c3再去解密
* @param c1c3c2
* @return
*/
private static byte[] ChangeC1C3C2ToC1C2C3(byte[] c1c3c2)
{
int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
const int c3Len = 32; //new SM3Digest().GetDigestSize();
byte[] result = new byte[c1c3c2.Length];
Buffer.BlockCopy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
Buffer.BlockCopy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.Length - c1Len - c3Len); //c2
Buffer.BlockCopy(c1c3c2, c1Len, result, c1c3c2.Length - c3Len, c3Len); //c3
return result;
} /**
* c1||c3||c2
* @param data
* @param key
* @return
*/
public static byte[] Sm2Decrypt(byte[] data, AsymmetricKeyParameter key)
{
return Sm2DecryptOld(ChangeC1C3C2ToC1C2C3(data), key);
} /**
* c1||c3||c2
* @param data
* @param key
* @return
*/ public static byte[] Sm2Encrypt(byte[] data, AsymmetricKeyParameter key)
{
return ChangeC1C2C3ToC1C3C2(Sm2EncryptOld(data, key));
} /**
* c1||c2||c3
* @param data
* @param key
* @return
*/
public static byte[] Sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey)
{
try
{
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(true, new ParametersWithRandom(pubkey, new SecureRandom()));
return sm2Engine.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
//log.Error("Sm2EncryptOld error: " + e.Message, e);
return null;
}
} /**
* c1||c2||c3
* @param data
* @param key
* @return
*/
public static byte[] Sm2DecryptOld(byte[] data, AsymmetricKeyParameter key)
{
try
{
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(false, key);
return sm2Engine.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
//log.Error("Sm2DecryptOld error: " + e.Message, e);
return null;
}
} /**
* @param bytes
* @return
*/
public static byte[] Sm3(byte[] bytes)
{
try
{
SM3Digest digest = new SM3Digest();
digest.BlockUpdate(bytes, 0, bytes.Length);
byte[] result = DigestUtilities.DoFinal(digest);
return result;
}
catch (Exception e)
{
//log.Error("Sm3 error: " + e.Message, e);
return null;
}
} private const int RS_LEN = 32; private static byte[] BigIntToFixexLengthBytes(BigInteger rOrS)
{
// for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
// r and s are the result of mod n, so they should be less than n and have length<=32
byte[] rs = rOrS.ToByteArray();
if (rs.Length == RS_LEN) return rs;
else if (rs.Length == RS_LEN + 1 && rs[0] == 0) return Arrays.CopyOfRange(rs, 1, RS_LEN + 1);
else if (rs.Length < RS_LEN)
{
byte[] result = new byte[RS_LEN];
Arrays.Fill(result, (byte)0);
Buffer.BlockCopy(rs, 0, result, RS_LEN - rs.Length, rs.Length);
return result;
}
else
{
throw new ArgumentException("err rs: " + Hex.ToHexString(rs));
}
} /**
* BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s
* @param rsDer rs in asn1 format
* @return sign result in plain byte array
*/
private static byte[] RsAsn1ToPlainByteArray(byte[] rsDer)
{
Asn1Sequence seq = Asn1Sequence.GetInstance(rsDer);
byte[] r = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[0]).Value);
byte[] s = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[1]).Value);
byte[] result = new byte[RS_LEN * 2];
Buffer.BlockCopy(r, 0, result, 0, r.Length);
Buffer.BlockCopy(s, 0, result, RS_LEN, s.Length);
return result;
} /**
* BC的SM3withSM2验签需要的rs是asn1格式的,这个方法将直接拼接r||s的字节数组转化成asn1格式
* @param sign in plain byte array
* @return rs result in asn1 format
*/
private static byte[] RsPlainByteArrayToAsn1(byte[] sign)
{
if (sign.Length != RS_LEN * 2) throw new ArgumentException("err rs. ");
BigInteger r = new BigInteger(1, Arrays.CopyOfRange(sign, 0, RS_LEN));
BigInteger s = new BigInteger(1, Arrays.CopyOfRange(sign, RS_LEN, RS_LEN * 2));
Asn1EncodableVector v = new Asn1EncodableVector();
v.Add(new DerInteger(r));
v.Add(new DerInteger(s));
try
{
return new DerSequence(v).GetEncoded("DER");
}
catch (IOException e)
{
//log.Error("RsPlainByteArrayToAsn1 error: " + e.Message, e);
return null;
}
} public static AsymmetricCipherKeyPair GenerateKeyPair()
{
try
{
ECKeyPairGenerator kpGen = new ECKeyPairGenerator();
kpGen.Init(new ECKeyGenerationParameters(ecDomainParameters, new SecureRandom()));
return kpGen.GenerateKeyPair();
}
catch (Exception e)
{
//log.Error("generateKeyPair error: " + e.Message, e);
return null;
}
} public static ECPrivateKeyParameters GetPrivatekeyFromD(BigInteger d)
{
return new ECPrivateKeyParameters(d, ecDomainParameters);
} public static ECPublicKeyParameters GetPublickeyFromXY(BigInteger x, BigInteger y)
{
return new ECPublicKeyParameters(x9ECParameters.Curve.CreatePoint(x, y), ecDomainParameters);
} public static AsymmetricKeyParameter GetPublickeyFromX509File(FileInfo file)
{ FileStream fileStream = null;
try
{
//file.DirectoryName + "\\" + file.Name
fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream);
return certificate.GetPublicKey();
}
catch (Exception e)
{
//log.Error(file.Name + "读取失败,异常:" + e);
}
finally
{
if (fileStream != null)
fileStream.Close();
}
return null;
} public class Sm2Cert
{
public AsymmetricKeyParameter privateKey;
public AsymmetricKeyParameter publicKey;
public String certId;
} private static byte[] ToByteArray(int i)
{
byte[] byteArray = new byte[4];
byteArray[0] = (byte)(i >> 24);
byteArray[1] = (byte)((i & 0xFFFFFF) >> 16);
byteArray[2] = (byte)((i & 0xFFFF) >> 8);
byteArray[3] = (byte)(i & 0xFF);
return byteArray;
} /**
* 字节数组拼接
*
* @param params
* @return
*/
private static byte[] Join(params byte[][] byteArrays)
{
List<byte> byteSource = new List<byte>();
for (int i = 0; i < byteArrays.Length; i++)
{
byteSource.AddRange(byteArrays[i]);
}
byte[] data = byteSource.ToArray();
return data;
} /**
* 密钥派生函数
*
* @param Z
* @param klen
* 生成klen字节数长度的密钥
* @return
*/
private static byte[] KDF(byte[] Z, int klen)
{
int ct = 1;
int end = (int)Math.Ceiling(klen * 1.0 / 32);
List<byte> byteSource = new List<byte>();
try
{
for (int i = 1; i < end; i++)
{
byteSource.AddRange(GmUtil.Sm3(Join(Z, ToByteArray(ct))));
ct++;
}
byte[] last = GmUtil.Sm3(Join(Z, ToByteArray(ct)));
if (klen % 32 == 0)
{
byteSource.AddRange(last);
}
else
byteSource.AddRange(Arrays.CopyOfRange(last, 0, klen % 32));
return byteSource.ToArray();
}
catch (Exception e)
{
//log.Error("KDF error: " + e.Message, e);
}
return null;
} public static byte[] Sm4DecryptCBC(byte[] keyBytes, byte[] cipher, byte[] iv, String algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (cipher.Length % 16 != 0) throw new ArgumentException("err data length"); try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
if (iv == null) iv = ZeroIv(algo);
c.Init(false, new ParametersWithIV(key, iv));
return c.DoFinal(cipher);
}
catch (Exception e)
{
//log.Error("Sm4DecryptCBC error: " + e.Message, e);
return null;
}
} public static byte[] Sm4EncryptCBC(byte[] keyBytes, byte[] plain, byte[] iv, String algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (plain.Length % 16 != 0) throw new ArgumentException("err data length"); try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
if (iv == null) iv = ZeroIv(algo);
c.Init(true, new ParametersWithIV(key, iv));
return c.DoFinal(plain);
}
catch (Exception e)
{
//log.Error("Sm4EncryptCBC error: " + e.Message, e);
return null;
}
} public static byte[] Sm4EncryptECB(byte[] keyBytes, byte[] plain, string algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (plain.Length % 16 != 0) throw new ArgumentException("err data length"); try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
c.Init(true, key);
return c.DoFinal(plain);
}
catch (Exception e)
{
//log.Error("Sm4EncryptECB error: " + e.Message, e);
return null;
}
} public static byte[] Sm4DecryptECB(byte[] keyBytes, byte[] cipher, string algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (cipher.Length % 16 != 0) throw new ArgumentException("err data length"); try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
c.Init(false, key);
return c.DoFinal(cipher);
}
catch (Exception e)
{
//log.Error("Sm4DecryptECB error: " + e.Message, e);
return null;
}
} public const String SM4_ECB_NOPADDING = "SM4/ECB/NoPadding";
public const String SM4_CBC_NOPADDING = "SM4/CBC/NoPadding";
public const String SM4_CBC_PKCS7PADDING = "SM4/CBC/PKCS7Padding"; /**
* cfca官网CSP沙箱导出的sm2文件
* @param pem 二进制原文
* @param pwd 密码
* @return
*/
public static Sm2Cert readSm2File(byte[] pem, String pwd)
{ Sm2Cert sm2Cert = new Sm2Cert();
try
{
Asn1Sequence asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(pem);
// ASN1Integer asn1Integer = (ASN1Integer) asn1Sequence.getObjectAt(0); //version=1
Asn1Sequence priSeq = (Asn1Sequence)asn1Sequence[1];//private key
Asn1Sequence pubSeq = (Asn1Sequence)asn1Sequence[2];//public key and x509 cert // ASN1ObjectIdentifier sm2DataOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(0);
// ASN1ObjectIdentifier sm4AlgOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(1);
Asn1OctetString priKeyAsn1 = (Asn1OctetString)priSeq[2];
byte[] key = KDF(System.Text.Encoding.UTF8.GetBytes(pwd), 32);
byte[] priKeyD = Sm4DecryptCBC(Arrays.CopyOfRange(key, 16, 32),
priKeyAsn1.GetOctets(),
Arrays.CopyOfRange(key, 0, 16), SM4_CBC_PKCS7PADDING);
sm2Cert.privateKey = GetPrivatekeyFromD(new BigInteger(1, priKeyD));
// log.Info(Hex.toHexString(priKeyD)); // ASN1ObjectIdentifier sm2DataOidPub = (ASN1ObjectIdentifier) pubSeq.getObjectAt(0);
Asn1OctetString pubKeyX509 = (Asn1OctetString)pubSeq[1];
X509Certificate x509 = (X509Certificate)new X509CertificateParser().ReadCertificate(pubKeyX509.GetOctets());
sm2Cert.publicKey = x509.GetPublicKey();
sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进账,有啥其他进制要求的自己改改
return sm2Cert;
}
catch (Exception e)
{
//log.Error("readSm2File error: " + e.Message, e);
return null;
}
} /**
*
* @param cert
* @return
*/
public static Sm2Cert ReadSm2X509Cert(byte[] cert)
{
Sm2Cert sm2Cert = new Sm2Cert();
try
{ X509Certificate x509 = new X509CertificateParser().ReadCertificate(cert);
sm2Cert.publicKey = x509.GetPublicKey();
sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进账,有啥其他进制要求的自己改改
return sm2Cert;
}
catch (Exception e)
{
//log.Error("ReadSm2X509Cert error: " + e.Message, e);
return null;
}
} public static byte[] ZeroIv(String algo)
{ try
{
IBufferedCipher cipher = CipherUtilities.GetCipher(algo);
int blockSize = cipher.GetBlockSize();
byte[] iv = new byte[blockSize];
Arrays.Fill(iv, (byte)0);
return iv;
}
catch (Exception e)
{
//log.Error("ZeroIv error: " + e.Message, e);
return null;
}
} public static void Main2(string[] s)
{ // 随便看看
//log.Info("GMNamedCurves: ");
foreach (string e in GMNamedCurves.Names)
{
//log.Info(e);
}
//log.Info("sm2p256v1 n:" + x9ECParameters.N);
//log.Info("sm2p256v1 nHex:" + Hex.ToHexString(x9ECParameters.N.ToByteArray())); // 生成公私钥对 ---------------------
AsymmetricCipherKeyPair kp = GmUtil.GenerateKeyPair();
//log.Info("private key d: " + ((ECPrivateKeyParameters)kp.Private).D);
//log.Info("public key q:" + ((ECPublicKeyParameters)kp.Public).Q); //{x, y, zs...} //签名验签
byte[] msg = System.Text.Encoding.UTF8.GetBytes("message digest");
byte[] userId = System.Text.Encoding.UTF8.GetBytes("userId");
byte[] sig = SignSm3WithSm2(msg, userId, kp.Private);
//log.Info("testSignSm3WithSm2: " + Hex.ToHexString(sig));
//log.Info("testVerifySm3WithSm2: " + VerifySm3WithSm2(msg, userId, sig, kp.Public)); // 由d生成私钥 ---------------------
BigInteger d = new BigInteger("097b5230ef27c7df0fa768289d13ad4e8a96266f0fcb8de40d5942af4293a54a", 16);
ECPrivateKeyParameters bcecPrivateKey = GetPrivatekeyFromD(d);
//log.Info("testGetFromD: " + bcecPrivateKey.D.ToString(16)); //公钥X坐标PublicKeyXHex: 59cf9940ea0809a97b1cbffbb3e9d96d0fe842c1335418280bfc51dd4e08a5d4
//公钥Y坐标PublicKeyYHex: 9a7f77c578644050e09a9adc4245d1e6eba97554bc8ffd4fe15a78f37f891ff8
AsymmetricKeyParameter publicKey = GetPublickeyFromX509File(new FileInfo("d:/certs/69629141652.cer"));
//log.Info(publicKey);
AsymmetricKeyParameter publicKey1 = GetPublickeyFromXY(new BigInteger("59cf9940ea0809a97b1cbffbb3e9d96d0fe842c1335418280bfc51dd4e08a5d4", 16), new BigInteger("9a7f77c578644050e09a9adc4245d1e6eba97554bc8ffd4fe15a78f37f891ff8", 16));
//log.Info("testReadFromX509File: " + ((ECPublicKeyParameters)publicKey).Q);
//log.Info("testGetFromXY: " + ((ECPublicKeyParameters)publicKey1).Q);
//log.Info("testPubKey: " + publicKey.Equals(publicKey1));
//log.Info("testPubKey: " + ((ECPublicKeyParameters)publicKey).Q.Equals(((ECPublicKeyParameters)publicKey1).Q)); // sm2 encrypt and decrypt test ---------------------
AsymmetricCipherKeyPair kp2 = GenerateKeyPair();
AsymmetricKeyParameter publicKey2 = kp2.Public;
AsymmetricKeyParameter privateKey2 = kp2.Private;
byte[] bs = Sm2Encrypt(System.Text.Encoding.UTF8.GetBytes("s"), publicKey2);
//log.Info("testSm2Enc dec: " + Hex.ToHexString(bs));
bs = Sm2Decrypt(bs, privateKey2);
//log.Info("testSm2Enc dec: " + System.Text.Encoding.UTF8.GetString(bs)); // sm4 encrypt and decrypt test ---------------------
//0123456789abcdeffedcba9876543210 + 0123456789abcdeffedcba9876543210 -> 681edf34d206965e86b3e94f536e4246
byte[] plain = Hex.Decode("0123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba9876543210");
byte[] key = Hex.Decode("0123456789abcdeffedcba9876543210");
byte[] cipher = Hex.Decode("595298c7c6fd271f0402f804c33d3f66");
bs = Sm4EncryptECB(key, plain, GmUtil.SM4_ECB_NOPADDING);
//log.Info("testSm4EncEcb: " + Hex.ToHexString(bs)); ;
bs = Sm4DecryptECB(key, bs, GmUtil.SM4_ECB_NOPADDING);
//log.Info("testSm4DecEcb: " + Hex.ToHexString(bs)); //读.sm2文件
String sm2 = "MIIDHQIBATBHBgoqgRzPVQYBBAIBBgcqgRzPVQFoBDDW5/I9kZhObxXE9Vh1CzHdZhIhxn+3byBU\nUrzmGRKbDRMgI3hJKdvpqWkM5G4LNcIwggLNBgoqgRzPVQYBBAIBBIICvTCCArkwggJdoAMCAQIC\nBRA2QSlgMAwGCCqBHM9VAYN1BQAwXDELMAkGA1UEBhMCQ04xMDAuBgNVBAoMJ0NoaW5hIEZpbmFu\nY2lhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEbMBkGA1UEAwwSQ0ZDQSBURVNUIFNNMiBPQ0Ex\nMB4XDTE4MTEyNjEwMTQxNVoXDTIwMTEyNjEwMTQxNVowcjELMAkGA1UEBhMCY24xEjAQBgNVBAoM\nCUNGQ0EgT0NBMTEOMAwGA1UECwwFQ1VQUkExFDASBgNVBAsMC0VudGVycHJpc2VzMSkwJwYDVQQD\nDCAwNDFAWnRlc3RAMDAwMTAwMDA6U0lHTkAwMDAwMDAwMTBZMBMGByqGSM49AgEGCCqBHM9VAYIt\nA0IABDRNKhvnjaMUShsM4MJ330WhyOwpZEHoAGfqxFGX+rcL9x069dyrmiF3+2ezwSNh1/6YqfFZ\nX9koM9zE5RG4USmjgfMwgfAwHwYDVR0jBBgwFoAUa/4Y2o9COqa4bbMuiIM6NKLBMOEwSAYDVR0g\nBEEwPzA9BghggRyG7yoBATAxMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmNmY2EuY29tLmNuL3Vz\nL3VzLTE0Lmh0bTA4BgNVHR8EMTAvMC2gK6AphidodHRwOi8vdWNybC5jZmNhLmNvbS5jbi9TTTIv\nY3JsNDI4NS5jcmwwCwYDVR0PBAQDAgPoMB0GA1UdDgQWBBREhx9VlDdMIdIbhAxKnGhPx8FcHDAd\nBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwDAYIKoEcz1UBg3UFAANIADBFAiEAgWvQi3h6\niW4jgF4huuXfhWInJmTTYr2EIAdG8V4M8fYCIBixygdmfPL9szcK2pzCYmIb6CBzo5SMv50Odycc\nVfY6";
bs = Convert.FromBase64String(sm2);
String pwd = "cfca1234";
GmUtil.Sm2Cert sm2Cert = GmUtil.readSm2File(bs, pwd);
//log.Info("testReadSm2File, pubkey: " + ((ECPublicKeyParameters)sm2Cert.publicKey).Q.ToString());
//log.Info("testReadSm2File, prikey: " + Hex.ToHexString(((ECPrivateKeyParameters)sm2Cert.privateKey).D.ToByteArray()));
//log.Info("testReadSm2File, certId: " + sm2Cert.certId); bs = Sm2Encrypt(System.Text.Encoding.UTF8.GetBytes("s"), ((ECPublicKeyParameters)sm2Cert.publicKey));
//log.Info("testSm2Enc dec: " + Hex.ToHexString(bs));
bs = Sm2Decrypt(bs, ((ECPrivateKeyParameters)sm2Cert.privateKey));
//log.Info("testSm2Enc dec: " + System.Text.Encoding.UTF8.GetString(bs)); msg = System.Text.Encoding.UTF8.GetBytes("message digest");
userId = System.Text.Encoding.UTF8.GetBytes("userId");
sig = SignSm3WithSm2(msg, userId, ((ECPrivateKeyParameters)sm2Cert.privateKey));
//log.Info("testSignSm3WithSm2: " + Hex.ToHexString(sig));
//log.Info("testVerifySm3WithSm2: " + VerifySm3WithSm2(msg, userId, sig, ((ECPublicKeyParameters)sm2Cert.publicKey)));
} }
}
C#调用DEMO:
//签名
private void btnSign_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(txtPrivateKey.Text) || string.IsNullOrWhiteSpace(txtUserId.Text) || string.IsNullOrWhiteSpace(txtToSignStr.Text))
{
MessageBox.Show("私钥,USERID,签名字符串不能为空。");
return;
} // 由d生成私钥 ---------------------
BigInteger d = new BigInteger(txtPrivateKey.Text, 16);
ECPrivateKeyParameters bcecPrivateKey = CommonUtils.GmUtil.GetPrivatekeyFromD(d);
byte[] userId = Encoding.UTF8.GetBytes(txtUserId.Text); byte[] msg = System.Text.Encoding.UTF8.GetBytes(txtToSignStr.Text);
byte[] sig = GmUtil.SignSm3WithSm2(msg, userId, bcecPrivateKey); //byte[] bytTmp = Hex.Decode(txtSign.Text);
txtSign.Text = Convert.ToBase64String(sig); string sign16 = Hex.ToHexString(sig);
}
catch (Exception ex)
{ MessageBox.Show(ex.Message);
}
} //验签
private void button1_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(txtPubKey.Text) || string.IsNullOrWhiteSpace(txtUserId.Text) || string.IsNullOrWhiteSpace(txtToSignStr.Text)
|| string.IsNullOrWhiteSpace(txtSign.Text))
{
MessageBox.Show("公钥,USERID,签名字符串,签名值不能为空。");
return;
}
//公钥128位,拆成2个64位。
string pa = txtPubKey.Text.Substring(0, 64);
string pb = txtPubKey.Text.Substring(64, 64); AsymmetricKeyParameter publicKey1 = GmUtil.GetPublickeyFromXY(new BigInteger(pa, 16), new BigInteger(pb, 16)); byte[] userId = Encoding.UTF8.GetBytes(txtUserId.Text);
byte[] msg = System.Text.Encoding.UTF8.GetBytes(txtToSignStr.Text);
//byte[] bytSig = Hex.Decode(txtSign.Text);
byte[] bytSig = Convert.FromBase64String(txtSign.Text);
bool bRst = GmUtil.VerifySm3WithSm2(msg, userId, bytSig, publicKey1);
if (bRst)
{
lblValidRst.Text = "验证:通过 "+DateTime.Now.ToString();
}
else
{
lblValidRst.Text = "验证:不通过 " + DateTime.Now.ToString();
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message);
}
}
JAVA
引用了commons-codec-1.9.jar (转换BASE64),bcprov-jdk15on-169.jar (国密算法 ,从Bouncy Castle官网下载)
工具类:
package org.lw; //import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jcajce.spec.SM2ParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
//import org.junit.Test; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.util.Arrays; //@Slf4j
public class SmUtil { private final static int RS_LEN = 32;
private static X9ECParameters x9ECParameters = GMNamedCurves.getByName("sm2p256v1");
private static ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters.getCurve(), x9ECParameters.getG(), x9ECParameters.getN());
private static ECParameterSpec ecParameterSpec = new ECParameterSpec(x9ECParameters.getCurve(), x9ECParameters.getG(), x9ECParameters.getN()); static {
if (Security.getProvider("BC") == null) {
Security.addProvider(new BouncyCastleProvider());
}
} /**
* 生成sm3摘要
*
* @param src
* @return
* @throws UnsupportedEncodingException
*/
public static String generateSM3HASH(String src) throws UnsupportedEncodingException {
byte[] md = new byte[32];
byte[] msg1 = src.getBytes("utf-8");
SM3Digest sm3 = new SM3Digest();
sm3.update(msg1, 0, msg1.length);
sm3.doFinal(md, 0);
String s = new String(Hex.encode(md)).toUpperCase();
// log.debug("SM3摘要:{}", s);
return s;
} public static String signSm3WithSm2(String msg, String userId, String privateKey) throws Exception {
BCECPrivateKey bcecPrivateKey = getPrivatekeyFromD(privateKey);
String sign = Base64.encodeBase64String(signSm3WithSm2(msg.getBytes("utf-8"), userId.getBytes("utf-8"), bcecPrivateKey));
// log.debug("生成的签名:{}", sign);
return sign;
} public static BCECPrivateKey getPrivatekeyFromD(String privateKey) {
ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(privateKey, 16), ecParameterSpec);
return new BCECPrivateKey("EC", ecPrivateKeySpec, BouncyCastleProvider.CONFIGURATION);
} /**
* @param msg
* @param userId
* @param privateKey
* @return r||s,直接拼接byte数组的rs
*/
public static byte[] signSm3WithSm2(byte[] msg, byte[] userId, PrivateKey privateKey) {
return rsAsn1ToPlainByteArray(signSm3WithSm2Asn1Rs(msg, userId, privateKey));
} /**
* @param msg
* @param userId
* @param privateKey
* @return rs in <b>asn1 format</b>
*/
public static byte[] signSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, PrivateKey privateKey) {
try {
SM2ParameterSpec parameterSpec = new SM2ParameterSpec(userId);
Signature signer = Signature.getInstance("SM3withSM2", "BC");
signer.setParameter(parameterSpec);
signer.initSign(privateKey, new SecureRandom());
signer.update(msg, 0, msg.length);
byte[] sig = signer.sign();
return sig;
} catch (Exception e) {
throw new RuntimeException(e);
}
} /**
* BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s
*
* @param rsDer rs in asn1 format
* @return sign result in plain byte array
*/
private static byte[] rsAsn1ToPlainByteArray(byte[] rsDer) {
ASN1Sequence seq = ASN1Sequence.getInstance(rsDer);
byte[] r = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(0)).getValue());
byte[] s = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(1)).getValue());
byte[] result = new byte[RS_LEN * 2];
System.arraycopy(r, 0, result, 0, r.length);
System.arraycopy(s, 0, result, RS_LEN, s.length);
return result;
} private static byte[] bigIntToFixexLengthBytes(BigInteger rOrS) {
// for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
// r and s are the result of mod n, so they should be less than n and have length<=32
byte[] rs = rOrS.toByteArray();
if (rs.length == RS_LEN) {
return rs;
} else if (rs.length == RS_LEN + 1 && rs[0] == 0) {
return Arrays.copyOfRange(rs, 1, RS_LEN + 1);
} else if (rs.length < RS_LEN) {
byte[] result = new byte[RS_LEN];
Arrays.fill(result, (byte) 0);
System.arraycopy(rs, 0, result, RS_LEN - rs.length, rs.length);
return result;
} else {
throw new RuntimeException("err rs: " + Hex.toHexString(rs));
}
} /**
* @param msg
* @param userId
* @param rs 签名
* @param publicKey
* @return
*/
public static boolean verifySm3WithSm2(String msg, String userId, String rs, String publicKey) throws Exception {
return verifySm3WithSm2(msg.getBytes("utf-8"), userId.getBytes("utf-8"), Base64.decodeBase64(rs), getBCECPublicKeyFromD(publicKey));
} /**
* @param msg
* @param userId
* @param rs r||s,直接拼接byte数组的rs
* @param publicKey
* @return
*/
public static boolean verifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, PublicKey publicKey) {
return verifySm3WithSm2Asn1Rs(msg, userId, rsPlainByteArrayToAsn1(rs), publicKey);
} /**
* BC的SM3withSM2验签需要的rs是asn1格式的,这个方法将直接拼接r||s的字节数组转化成asn1格式
*
* @param sign in plain byte array
* @return rs result in asn1 format
*/
private static byte[] rsPlainByteArrayToAsn1(byte[] sign) {
if (sign.length != RS_LEN * 2) {
throw new RuntimeException("err rs. ");
}
BigInteger r = new BigInteger(1, Arrays.copyOfRange(sign, 0, RS_LEN));
BigInteger s = new BigInteger(1, Arrays.copyOfRange(sign, RS_LEN, RS_LEN * 2));
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(r));
v.add(new ASN1Integer(s));
try {
return new DERSequence(v).getEncoded("DER");
} catch (IOException e) {
throw new RuntimeException(e);
}
} /**
* @param msg
* @param userId
* @param rs in <b>asn1 format</b>
* @param publicKey
* @return
*/
public static boolean verifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] rs, PublicKey publicKey) {
try {
SM2ParameterSpec parameterSpec = new SM2ParameterSpec(userId);
Signature verifier = Signature.getInstance("SM3withSM2", new BouncyCastleProvider());
verifier.setParameter(parameterSpec);
verifier.initVerify(publicKey);
verifier.update(msg, 0, msg.length);
return verifier.verify(rs);
} catch (Exception e) {
throw new RuntimeException(e);
}
} /**
* 转成公钥对象
*
* @param pubKey
* @return
*/
public static PublicKey getBCECPublicKeyFromD(String pubKey) throws Exception {
//TODO 不知道为什么在公钥前加04才不会有问题
final String prefix = "04";
if (!pubKey.startsWith(prefix)) {
pubKey = prefix + pubKey;
}
// 将公钥HEX字符串转换为椭圆曲线对应的点
ECPoint ecPoint = x9ECParameters.getCurve().decodePoint(Hex.decode(pubKey));
ECPublicKeySpec eCPublicKeySpec = new ECPublicKeySpec(ecPoint, ecParameterSpec);
return new BCECPublicKey("EC", eCPublicKeySpec, BouncyCastleProvider.CONFIGURATION); } // /**
// * 国密公私钥生成
// *
// * @throws NoSuchAlgorithmException
// * @throws InvalidAlgorithmParameterException
// */
// @Test
// public void test11() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
// // 获取SM2椭圆曲线的参数
// final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
// // 获取一个椭圆曲线类型的密钥对生成器
// final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
// // 使用SM2参数初始化生成器
// kpg.initialize(sm2Spec);
//
// // 使用SM2的算法区域初始化密钥生成器
// kpg.initialize(sm2Spec, new SecureRandom());
// // 获取密钥对
// KeyPair keyPair = kpg.generateKeyPair();
//
// log.info(Hex.toHexString(((BCECPrivateKey) keyPair.getPrivate()).getD().toByteArray()));
// log.info(Hex.toHexString(((BCECPublicKey) keyPair.getPublic()).getQ().getEncoded(false)));
// } }
JAVA调用 DEMO:
package org.lw; import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date; public class Main { public static void main(String[] args) { //国密 私钥
String strPrivateKey = "022A88CD5B5B3F56500615EF380C245CE81F32E980BB0CC708D01F9BD8558FEF";
//国密 userId
String strUserId = "123456789";
//待签名内容
String strBody = "签名报文字符串123456"; try {
//签名值
String strSign = SmUtil.signSm3WithSm2(strBody, strUserId, strPrivateKey);
System.out.println(getNow() + " 签名结果:" + strSign); //C#.NET 签名值
// strSign="aBqRJHtnPJvYJNL6C+KoH0BGYmO+3tRJ/IK5TYHuxdqcD41Nr5z2/bq1zx3m2nrPxB/imLpIUQmR/EpubiS/Ig==";
//国密 公钥
String strPubKey = "3D3AA4732B56DFCC643CF1B0ABAF75EF9EC16A756C18967090E8250E0A49915EEFDD5CBE16BB34CC93B20D3EFB4C842FFCE13887FE211DAE33DFD2AD025265D6";
//验证签名
boolean bRst = SmUtil.verifySm3WithSm2(strBody, strUserId, strSign, strPubKey);
System.out.println(getNow() + " 验证签名:" + bRst);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
} public static String getNow() {
String formatStr = "yyyy-MM-dd HH:mm:ss.SSS";
LocalDateTime lnow = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);
String nowFormat = lnow.format(dateTimeFormatter);
return nowFormat;
} }
C#和JAVA,使用的私钥,公钥,userId,待签名字符串是一致的。
私钥:022A88CD5B5B3F56500615EF380C245CE81F32E980BB0CC708D01F9BD8558FEF
公钥:3D3AA4732B56DFCC643CF1B0ABAF75EF9EC16A756C18967090E8250E0A49915EEFDD5CBE16BB34CC93B20D3EFB4C842FFCE13887FE211DAE33DFD2AD025265D6
userId:123456789
待签名字符串:签名报文字符串123456
C#和JAVA源码地址:https://gitee.com/runliuv/mypub/tree/master/donetproj
"donet国密签名SM3withSM2"文件夹。
javagm 是JAVA 项目,用IDEA 社区版打开。
WindowsForms国密GmUtil 是C#.NET 项目,用VS2015及以上打开。
(图1)
(图2)
C#.NET 国密SM3withSM2签名与验签 和JAVA互通的更多相关文章
- erlang的RSA签名与验签
1.RSA介绍 RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对 其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥,即公钥,而 ...
- .NET RSA解密、签名、验签
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Sec ...
- PHP SHA1withRSA加密生成签名及验签
最近公司对接XX第三方支付平台的代付业务,由于对方公司只有JAVA的demo,所以只能根据文档自己整合PHP的签名加密,网上找过几个方法,踩到各种各样的坑,还好最后算是搞定了,话不多说,代码分享出来. ...
- 中行P1签名及验签
分享中国银行快捷.NET P1签名和验签方法代码中ReturnValue为自定义类型请无视 #region 验证签名 /// <summary> /// 验证签名 /// </sum ...
- 几个例子理解对称加密与非对称加密、公钥与私钥、签名与验签、数字证书、HTTPS加密方式
# 原创,转载请留言联系 为什么会出现这么多加密啊,公钥私钥啊,签名啊这些东西呢?说到底还是保证双方通信的安全性与完整性.例如小明发一封表白邮件给小红,他总不希望给别人看见吧.而各种各样的技术就是为了 ...
- Delphi微信支付【支持MD5和HMAC-SHA256签名与验签】
作者QQ:(648437169) 点击下载➨微信支付 微信支付api文档 [Delphi 微信支付]支持付款码支付.二维码支付.订单查询.申请退款.退款查询.撤销订单.关闭订单. ...
- Delphi支付宝支付【支持SHA1WithRSA(RSA)和SHA256WithRSA(RSA2)签名与验签】
作者QQ:(648437169) 点击下载➨Delphi支付宝支付 支付宝支付api文档 [Delphi支付宝支付]支持条码支付.扫码支付.交易查询.交易退款.退款查询.交易撤 ...
- RSA后台签名前台验签的应用(前台采用jsrsasign库)
写在前面 安全测试需要, 为防止后台响应数据返给前台过程中被篡改前台再拿被篡改后的数据进行接下来的操作影响正常业务, 决定采用RSA对响应数据进行签名和验签, 于是有了这篇<RSA后台签名前台验 ...
- Delphi RSA签名与验签【支持SHA1WithRSA(RSA1)、SHA256WithRSA(RSA2)和MD5WithRSA签名与验签】
作者QQ:(648437169) 点击下载➨ RSA签名与验签 [delphi RSA签名与验签]支持3种方式签名与验签(SHA1WithRSA(RSA1).SHA256WithRSA(RSA2)和M ...
随机推荐
- Ckeditor 缺少图像源文件地址的解决 笨笨的人都看啦!
Ckeditor 本文是关于CKEditor 无法上传图片问题的一个解决.我大致写了一下遇到问题的过程,问题的出处,怎么解决的,原因是什么. 希望能够帮到有需要的大家,有些时候找不到问题的答案,真的是 ...
- NX二次开发-从一个坐标系到另一个坐标系的转换
函数:UF_MTX4_csys_to_csys().UF_MTX4_vec3_multiply() 函数说明:从一个坐标系统到另一个坐标系统的转换.如下图红色坐标系下有个红色的点,将红色的点转到绿色的 ...
- 【SQLite】SQLite文件突然变大怎么办?瘦身办法
使用VACUUM命令即可: VACUUM 命令通过复制主数据库中的内容到一个临时数据库文件,然后清空主数据库,并从副本中重新载入原始的数据库文件.这消除了空闲页,把表中的数据排列为连续的,另外会清理数 ...
- 搞清楚Spring事件机制后:Spring的源码看起来简单多了
本文主讲Spring的事件机制,意图说清楚: 什么是观察者模式? 自己实现事件驱动编程,对标Spring的事件机制 彻底搞懂Spring中的事件机制,从而让大家 本文内容较长,代码干货较多,建议收藏后 ...
- iNeuOS工业互联网平台,在高校教学实训领域的应用
目 录 1. 概述... 2 2. 实训柜... 2 3. 培训内容... 4 4. 二次开发培训... 5 1. 概述 中国工业互联网从 0 ...
- PL/SQL连不上,报 ORA-12170:TNS 连接超时
排错步骤: 1.查看网络是否通畅 打开cmd, ping 数据库IP 2. 查看端口是否通畅 打开cmd,tnsping 数据库IP 如果piing不通,可能是防火墙问题 3.检查防火墙状态 #ser ...
- 本地SQL Server怎么连接服务器上的数据库
在阿里云的安全组规则中的入方向加上端口1433就好了,首先得要有这个,其他的都是后话
- 【C语言】整型在内存中的存储
整型在内存中的存储 1.整型的归类 char short int long 以上都分为有符号(signed)与无符号(unsigned)的类型 2.原码.反码和补码 2.1 定义 计算机在表示一个数字 ...
- Spring学习日记01_IOC_xml的三种注入方式
什么是IOC 控制反转,把对象创建和对象之间的调用过程,交给Spring进行管理 使用IOC目的:为了耦合度降低 做入门案例就是IOC实现 IOC底层原理 xml解析 工厂模式 反射 原始方式 cla ...
- 关于Word转Markdown的工具Writage安装及使用
简介 Writage是为希望开始编写结构良好的文档,没有时间或不想深入了解 Markdown 语法的详细信息,或者更愿意使用 Word 作为文本编辑器的每个人设计的 下载并安装 安装包地址:https ...