基于bc 实现hex格式数据的SM2验签,bc 采用 bcprov-jdk16-1.46.jar ,demo下载链接
/**
* 模拟服务器SM2 验证签名
* @author ching
*
*/
public class Test {
public static void main(String[] args) throws Exception {
byte[] sourceData = "操作类型:二维码限额管理;172308727727".getBytes();
// 国密规范测试公钥
String pubk = "ea09946855fd7a8e444a558dfc9a79efb5a61850265bceb12d736be6758e7898785a67424443ee58aedffab653189c60172fa80da157bb6e201c18f179261570";
String pubkS = new String(Base64.encode(Util.hexToByte(pubk)));
System.out.println("pubkS: " + pubkS);
System.out.println("");
byte[] c = Util.hexToByte(
"3046022100E8E3D56F060C1E29E3A80EBF2687E39B038EBC946B235125C055C66A0D785802022100EE6E92DE1719D35BF9FF68B9022C6F2091347A9F1A987AA85FD53CB07ECCA1C0");
System.out.println("验签: ");
boolean vs = SM2Utils.verifySign(Base64.decode(pubkS.getBytes()), sourceData, c);
System.out.println("验签结果: " + vs);
System.out.println("");
}
}
SM2实现
import java.math.BigInteger;
import java.security.SecureRandom;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECFieldElement;
import org.bouncycastle.math.ec.ECFieldElement.Fp;
import org.bouncycastle.math.ec.ECPoint;
public class SM2
{
// 测试参数
// public static final String[] ecc_param = {
// "8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3",
// "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498",
// "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A",
// "8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7",
// "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D",
// "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2"
// };
// 正式参数
public static String[] ecc_param = {
"FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF",
"FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC",
"28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93",
"FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123",
"32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7",
"BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0"
};
public static SM2 Instance()
{
return new SM2();
}
public final BigInteger ecc_p;
public final BigInteger ecc_a;
public final BigInteger ecc_b;
public final BigInteger ecc_n;
public final BigInteger ecc_gx;
public final BigInteger ecc_gy;
public final ECCurve ecc_curve;
public final ECPoint ecc_point_g;
public final ECDomainParameters ecc_bc_spec;
public final ECKeyPairGenerator ecc_key_pair_generator;
public final ECFieldElement ecc_gx_fieldelement;
public final ECFieldElement ecc_gy_fieldelement;
public SM2()
{
this.ecc_p = new BigInteger(ecc_param[0], 16);
this.ecc_a = new BigInteger(ecc_param[1], 16);
this.ecc_b = new BigInteger(ecc_param[2], 16);
this.ecc_n = new BigInteger(ecc_param[3], 16);
this.ecc_gx = new BigInteger(ecc_param[4], 16);
this.ecc_gy = new BigInteger(ecc_param[5], 16);
this.ecc_gx_fieldelement = new Fp(this.ecc_p, this.ecc_gx);
this.ecc_gy_fieldelement = new Fp(this.ecc_p, this.ecc_gy);
this.ecc_curve = new ECCurve.Fp(this.ecc_p, this.ecc_a, this.ecc_b);
this.ecc_point_g = new ECPoint.Fp(this.ecc_curve, this.ecc_gx_fieldelement, this.ecc_gy_fieldelement);
this.ecc_bc_spec = new ECDomainParameters(this.ecc_curve, this.ecc_point_g, this.ecc_n);
ECKeyGenerationParameters ecc_ecgenparam;
ecc_ecgenparam = new ECKeyGenerationParameters(this.ecc_bc_spec, new SecureRandom());
this.ecc_key_pair_generator = new ECKeyPairGenerator();
this.ecc_key_pair_generator.init(ecc_ecgenparam);
}
public byte[] sm2GetZ(byte[] userId, ECPoint userKey)
{
SM3Digest sm3 = new SM3Digest();
int len = userId.length * 8;
sm3.update((byte) (len >> 8 & 0xFF));
sm3.update((byte) (len & 0xFF));
sm3.update(userId, 0, userId.length);
byte[] p = Util.byteConvert32Bytes(ecc_a);
sm3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(ecc_b);
sm3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(ecc_gx);
sm3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(ecc_gy);
sm3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(userKey.getX().toBigInteger());
sm3.update(p, 0, p.length);
p = Util.byteConvert32Bytes(userKey.getY().toBigInteger());
sm3.update(p, 0, p.length);
byte[] md = new byte[sm3.getDigestSize()];
sm3.doFinal(md, 0);
return md;
}
public void sm2Sign(byte[] md, BigInteger userD, ECPoint userKey, SM2Result sm2Result)
{
BigInteger e = new BigInteger(1, md);
BigInteger k = null;
ECPoint kp = null;
BigInteger r = null;
BigInteger s = null;
do
{
do
{
// 正式环境
// AsymmetricCipherKeyPair keypair = ecc_key_pair_generator.generateKeyPair();
// ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) keypair.getPrivate();
// ECPublicKeyParameters ecpub = (ECPublicKeyParameters) keypair.getPublic();
// k = ecpriv.getD();
// kp = ecpub.getQ();
k = userD;
kp = userKey;
// 国密规范测试 随机数k
// String kS = "6CB28D99385C175C94F94E934817663FC176D925DD72B727260DBAAE1FB2F96F";
// k = new BigInteger(kS, 16);
// kp = this.ecc_point_g.multiply(k);
System.out.println("计算曲线点X1: " + kp.getX().toBigInteger().toString(16));
System.out.println("计算曲线点Y1: " + kp.getY().toBigInteger().toString(16));
System.out.println("");
// r
r = e.add(kp.getX().toBigInteger());
r = r.mod(ecc_n);
} while (r.equals(BigInteger.ZERO) || r.add(k).equals(ecc_n));
// (1 + dA)~-1
BigInteger da_1 = userD.add(BigInteger.ONE);
da_1 = da_1.modInverse(ecc_n);
// s
s = r.multiply(userD);
s = k.subtract(s).mod(ecc_n);
s = da_1.multiply(s).mod(ecc_n);
} while (s.equals(BigInteger.ZERO));
sm2Result.r = r;
sm2Result.s = s;
}
public void sm2Verify(byte md[], ECPoint userKey, BigInteger r, BigInteger s, SM2Result sm2Result)
{
sm2Result.R = null;
BigInteger e = new BigInteger(1, md);
BigInteger t = r.add(s).mod(ecc_n);
if(t.equals(BigInteger.ZERO))
{
return;
}
else
{
ECPoint x1y1 = ecc_point_g.multiply(sm2Result.s);
System.out.println("计算曲线点X0: " + x1y1.getX().toBigInteger().toString(16));
System.out.println("计算曲线点Y0: " + x1y1.getY().toBigInteger().toString(16));
System.out.println("");
x1y1 = x1y1.add(userKey.multiply(t));
System.out.println("计算曲线点X1: " + x1y1.getX().toBigInteger().toString(16));
System.out.println("计算曲线点Y1: " + x1y1.getY().toBigInteger().toString(16));
System.out.println("");
sm2Result.R = e.add(x1y1.getX().toBigInteger()).mod(ecc_n);
System.out.println("R: " + sm2Result.R.toString(16));
return;
}
}
}
Sm2KeyPair 密钥实现
/**
* Created by yuhc on 16-2-21.
*/
public class Sm2KeyPair {
private byte[] priKey;
private byte[] pubKey;
public Sm2KeyPair(byte[] priKey, byte[] pubKey){
this.priKey = priKey;
this.pubKey = pubKey;
}
public byte[] getPriKey() {
return priKey;
}
public void setPriKey(byte[] priKey) {
this.priKey = priKey;
}
public byte[] getPubKey() {
return pubKey;
}
public void setPubKey(byte[] pubKey) {
this.pubKey = pubKey;
}
}
SM2Result实现
import java.math.BigInteger;
import org.bouncycastle.math.ec.ECPoint;
public class SM2Result
{
public SM2Result() {
}
// 签名/验签
public BigInteger r;
public BigInteger s;
public BigInteger R;
// 密钥交换
public byte[] sa;
public byte[] sb;
public byte[] s1;
public byte[] s2;
public ECPoint keyra;
public ECPoint keyrb;
}
SM2Utils实现:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Enumeration;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Base64;
public class SM2Utils
{
public static byte[] encrypt(byte[] publicKey, byte[] data)
{
if (publicKey == null || publicKey.length == 0)
{
return null;
}
if (data == null || data.length == 0)
{
return null;
}
byte[] source = new byte[data.length];
System.arraycopy(data, 0, source, 0, data.length);
byte[] formatedPubKey;
if (publicKey.length == 64){
//添加�?字节标识,用于ECPoint解析
formatedPubKey = new byte[65];
formatedPubKey[0] = 0x04;
System.arraycopy(publicKey,0,formatedPubKey,1,publicKey.length);
}
else
formatedPubKey = publicKey;
Cipher cipher = new Cipher();
SM2 sm2 = SM2.Instance();
ECPoint userKey = sm2.ecc_curve.decodePoint(formatedPubKey);
ECPoint c1 = cipher.Init_enc(sm2, userKey);
cipher.Encrypt(source);
byte[] c3 = new byte[32];
cipher.Dofinal(c3);
DERInteger x = new DERInteger(c1.getX().toBigInteger());
DERInteger y = new DERInteger(c1.getY().toBigInteger());
DEROctetString derDig = new DEROctetString(c3);
DEROctetString derEnc = new DEROctetString(source);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(x);
v.add(y);
v.add(derDig);
v.add(derEnc);
DERSequence seq = new DERSequence(v);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DEROutputStream dos = new DEROutputStream(bos);
try {
dos.writeObject(seq);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static byte[] decrypt(byte[] privateKey, byte[] encryptedData)
{
if (privateKey == null || privateKey.length == 0)
{
return null;
}
if (encryptedData == null || encryptedData.length == 0)
{
return null;
}
byte[] enc = new byte[encryptedData.length];
System.arraycopy(encryptedData, 0, enc, 0, encryptedData.length);
SM2 sm2 = SM2.Instance();
BigInteger userD = new BigInteger(1, privateKey);
ByteArrayInputStream bis = new ByteArrayInputStream(enc);
ASN1InputStream dis = new ASN1InputStream(bis);
try {
DERObject derObj = dis.readObject();
ASN1Sequence asn1 = (ASN1Sequence) derObj;
DERInteger x = (DERInteger) asn1.getObjectAt(0);
DERInteger y = (DERInteger) asn1.getObjectAt(1);
ECPoint c1 = sm2.ecc_curve.createPoint(x.getValue(), y.getValue(), true);
Cipher cipher = new Cipher();
cipher.Init_dec(userD, c1);
DEROctetString data = (DEROctetString) asn1.getObjectAt(3);
enc = data.getOctets();
cipher.Decrypt(enc);
byte[] c3 = new byte[32];
cipher.Dofinal(c3);
return enc;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 使用默认ID计算
* @param privateKey
* @param sourceData
* @return
*/
public static byte[] sign(byte[] privateKey, byte[] sourceData){
String userId = "1234567812345678";
return sign(userId.getBytes(), privateKey, sourceData);
}
public static byte[] sign(byte[] userId, byte[] privateKey, byte[] sourceData)
{
if (privateKey == null || privateKey.length == 0)
{
return null;
}
if (sourceData == null || sourceData.length == 0)
{
return null;
}
SM2 sm2 = SM2.Instance();
BigInteger userD = new BigInteger(privateKey);
System.out.println("userD: " + userD.toString(16));
System.out.println("");
ECPoint userKey = sm2.ecc_point_g.multiply(userD);
System.out.println("椭圆曲线点X: " + userKey.getX().toBigInteger().toString(16));
System.out.println("椭圆曲线点Y: " + userKey.getY().toBigInteger().toString(16));
System.out.println("");
SM3Digest sm3 = new SM3Digest();
byte[] z = sm2.sm2GetZ(userId, userKey);
System.out.println("SM3摘要Z: " + Util.getHexString(z));
System.out.println("");
System.out.println("M: " + Util.getHexString(sourceData));
System.out.println("");
sm3.update(z, 0, z.length);
sm3.update(sourceData, 0, sourceData.length);
byte[] md = new byte[32];
sm3.doFinal(md, 0);
System.out.println("SM3摘要�?: " + Util.getHexString(md));
System.out.println("");
SM2Result sm2Result = new SM2Result();
sm2.sm2Sign(md, userD, userKey, sm2Result);
System.out.println("r: " + sm2Result.r.toString(16));
System.out.println("s: " + sm2Result.s.toString(16));
System.out.println("");
DERInteger d_r = new DERInteger(sm2Result.r);
DERInteger d_s = new DERInteger(sm2Result.s);
ASN1EncodableVector v2 = new ASN1EncodableVector();
v2.add(d_r);
v2.add(d_s);
DERObject sign = new DERSequence(v2);
return sign.getDEREncoded();
}
/**
* 使用默认id计算
* @param publicKey
* @param sourceData
* @param signData
* @return
*/
public static boolean verifySign(byte[] publicKey, byte[] sourceData, byte[] signData){
String userId = "1234567812345678";
return verifySign(userId.getBytes(),publicKey,sourceData,signData);
}
@SuppressWarnings("unchecked")
public static boolean verifySign(byte[] userId, byte[] publicKey, byte[] sourceData, byte[] signData)
{
if (publicKey == null || publicKey.length == 0)
{
return false;
}
if (sourceData == null || sourceData.length == 0)
{
return false;
}
byte[] formatedPubKey;
if (publicKey.length == 64){
//添加�?字节标识,用于ECPoint解析
formatedPubKey = new byte[65];
formatedPubKey[0] = 0x04;
System.arraycopy(publicKey,0,formatedPubKey,1,publicKey.length);
}
else
formatedPubKey = publicKey;
SM2 sm2 = SM2.Instance();
ECPoint userKey = sm2.ecc_curve.decodePoint(formatedPubKey);
SM3Digest sm3 = new SM3Digest();
byte[] z = sm2.sm2GetZ(userId, userKey);
sm3.update(z, 0, z.length);
sm3.update(sourceData, 0, sourceData.length);
byte[] md = new byte[32];
sm3.doFinal(md, 0);
System.out.println("SM3摘要�?: " + Util.getHexString(md));
System.out.println("");
ByteArrayInputStream bis = new ByteArrayInputStream(signData);
ASN1InputStream dis = new ASN1InputStream(bis);
SM2Result sm2Result = null;
try {
DERObject derObj = dis.readObject();
Enumeration<DERInteger> e = ((ASN1Sequence) derObj).getObjects();
BigInteger r = ((DERInteger)e.nextElement()).getValue();
BigInteger s = ((DERInteger)e.nextElement()).getValue();
sm2Result = new SM2Result();
sm2Result.r = r;
sm2Result.s = s;
System.out.println("r: " + sm2Result.r.toString(16));
System.out.println("s: " + sm2Result.s.toString(16));
System.out.println("");
sm2.sm2Verify(md, userKey, sm2Result.r, sm2Result.s, sm2Result);
return sm2Result.r.equals(sm2Result.R);
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}
public static void main(String[] args) throws Exception
{
String plainText = "message digest";
byte[] sourceData = plainText.getBytes();
// 国密规范测试私钥
String prik = "444E6EA3EE0C7E0AAA5EE5C6BBC7A2D8DE3FB3FA990AD470232D07FB445F92D7";
String prikS = new String(Base64.encode(Util.hexToByte(prik)));
System.out.println("prikS: " + prikS);
System.out.println("");
// 国密规范测试用户ID
String userId = "1234567812345678";
System.out.println("ID: " + Util.getHexString(userId.getBytes()));
System.out.println("");
System.out.println("签名: ");
byte[] c = SM2Utils.sign(userId.getBytes(), Base64.decode(prikS.getBytes()), sourceData);
System.out.println("sign: " + Util.getHexString(c));
System.out.println("");
sourceData = "<?xml version='1.0' encoding='utf-8'?><t><d><M><k>转出帐号:</k><v>1014 5101 0100 0005 1321 5</v></M><M><k>转入帐号:</k><v>6212 8060 1000 4100 061</v></M><M><k>转入户名:</k><v>白素�?</v></M><M><k>金额:</k><v>1.00</v></M></d></t>".getBytes();
// 国密规范测试公钥
// String pubk = "2E9173C4DB1DB0B22980DD3235ABF99B787DE8E5C6D08BDBA4503D61EE2B32F0F7083CC46D92DAE72FD0223305D0B44A95D438142C45382B23B2A58122E1F3DF";
String pubk = "b96fa0249b43ca3cea944d92ed97d6688107c84525b271704f604133a0fc05ef0b59850e9920a7a4f2a1170aeb44a3aa18bff223125754d218a930f7df5f6f33";
String pubkS = new String(Base64.encode(Util.hexToByte(pubk)));
System.out.println("pubkS: " + pubkS);
System.out.println("");
c= Util.hexToByte("3045022100cbbe02d89cd21c74f5b16355752e11777c64a18f44363746013ab1cdc46a05540220563730d0faebfb29a752352662d5aeb0de4c1b9f40f73c2808bbfd2c7dfabde7");
System.out.println("验签: ");
boolean vs = SM2Utils.verifySign(Base64.decode(pubkS.getBytes()), sourceData, c);
System.out.println("验签结果: " + vs);
System.out.println("");
}
public static Sm2KeyPair generateKeyPair(){
SM2 sm2 = SM2.Instance();
AsymmetricCipherKeyPair keypair = sm2.ecc_key_pair_generator.generateKeyPair();
ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) keypair.getPrivate();
ECPublicKeyParameters ecpub = (ECPublicKeyParameters) keypair.getPublic();
// System.out.println("私钥: " + ecpriv.getD().toString(16).toUpperCase());
// System.out.println("公钥: " + ecpub.getQ().getX().toBigInteger().toString(16).toUpperCase() +
// ecpub.getQ().getY().toBigInteger().toString(16).toUpperCase());
byte[] priKey = new byte[32];
byte[] pubKey = new byte[64];
byte[] bigNumArray = ecpriv.getD().toByteArray();
System.arraycopy(bigNumArray, bigNumArray[0]==0?1:0, priKey, 0, 32);
System.arraycopy(ecpub.getQ().getEncoded(), 1, pubKey, 0, 64);
// System.out.println("私钥bigNumArray: " + Util.getHexString(bigNumArray));
// System.out.println("私钥: " + Util.getHexString(priKey));
// System.out.println("公钥: " + Util.getHexString(pubKey));
return new Sm2KeyPair(priKey, pubKey);
}
public static void main(){
String plainText = "Hello SM !";
byte[] sourceData = plainText.getBytes();
// 国密规范测试私钥
String prik = "444E6EA3EE0C7E0AAA5EE5C6BBC7A2D8DE3FB3FA990AD470232D07FB445F92D7";
byte[] c = SM2Utils.sign(Util.hexToByte(prik), sourceData);
System.out.println("sign: " + Util.getHexString(c));
// 国密规范测试公钥
String pubk = "2E9173C4DB1DB0B22980DD3235ABF99B787DE8E5C6D08BDBA4503D61EE2B32F0F7083CC46D92DAE72FD0223305D0B44A95D438142C45382B23B2A58122E1F3DF";
boolean vs = SM2Utils.verifySign(Util.hexToByte(pubk), sourceData, c);
System.out.println("验签结果: " + vs);
System.out.println("加密: ");
byte[] cipherText = SM2Utils.encrypt(Util.hexToByte(pubk), sourceData);
System.out.println(Util.getHexString(cipherText));
System.out.println("解密: ");
plainText = new String(SM2Utils.decrypt(Util.hexToByte(prik), cipherText));
System.out.println(plainText);
}
public static void Sm2Test(){
String plainText = "Hello SM !";
byte[] sourceData = plainText.getBytes();
Sm2KeyPair keyPair = generateKeyPair();
System.out.println("私钥: " + Util.getHexString(keyPair.getPriKey()));
System.out.println("公钥: " + Util.getHexString(keyPair.getPubKey()));
byte[] c = SM2Utils.sign(keyPair.getPriKey(), sourceData);
System.out.println("sign: " + Util.getHexString(c));
boolean vs = SM2Utils.verifySign(keyPair.getPubKey(), sourceData, c);
System.out.println("验签结果: " + vs);
System.out.println("加密: ");
byte[] cipherText = SM2Utils.encrypt(keyPair.getPubKey(), sourceData);
System.out.println(Util.getHexString(cipherText));
System.out.println("解密: ");
plainText = new String(SM2Utils.decrypt(keyPair.getPriKey(), cipherText));
System.out.println(plainText);
}
}