由于很多同学想做伸手党,此处重新上传了一个完整版的代码。包含了生成随机秘钥对,数据加密,数据解密,签名与验签例子,并给出了使用姿势。使用者需要使用maven导入项目,然后运行SM2Utils里面的main方法即可
package com.test;import org.bouncycastle.asn1.*;import org.bouncycastle.crypto.AsymmetricCipherKeyPair;import org.bouncycastle.crypto.digests.SM3Digest;import org.bouncycastle.crypto.params.ECPrivateKeyParameters;import org.bouncycastle.crypto.params.ECPublicKeyParameters;import org.bouncycastle.math.ec.ECPoint;import org.bouncycastle.util.encoders.Base64;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.math.BigInteger;import java.util.Enumeration;public class SM2Utils { public SM2Utils() { } /** * 生成随机秘钥对 */ public MyKeyPair generateKeyPair() { SM2 sm2 = SM2.Instance(); AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.generateKeyPair(); ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) key.getPrivate(); ECPublicKeyParameters ecpub = (ECPublicKeyParameters) key.getPublic(); BigInteger privateKey = ecpriv.getD(); org.bouncycastle.math.ec.ECPoint publicKey = ecpub.getQ(); SM2Utils.MyKeyPair myKeyPair = new SM2Utils.MyKeyPair(); myKeyPair.setPrivateKey(Util.byteToHex(privateKey.toByteArray())); myKeyPair.setPublicKey(Util.byteToHex(publicKey.getEncoded())); return myKeyPair; } /** * 数据加密 * @param publicKey * @param data * @return * @throws IOException */ public static byte[] encrypt(byte[] publicKey, byte[] data) throws IOException { if (publicKey != null && publicKey.length != 0) { if (data != null && data.length != 0) { byte[] source = new byte[data.length]; System.arraycopy(data, 0, source, 0, data.length); Cipher cipher = new Cipher(); SM2 sm2 = SM2.Instance(); org.bouncycastle.math.ec.ECPoint userKey = sm2.ecc_curve.decodePoint(publicKey); org.bouncycastle.math.ec.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); dos.writeObject(seq); return bos.toByteArray(); } else { return null; } } else { return null; } } /** * 数据解密 * @param privateKey * @param encryptedData * @return * @throws IOException */ public static byte[] decrypt(byte[] privateKey, byte[] encryptedData) throws IOException { if (privateKey != null && privateKey.length != 0) { if (encryptedData != null && encryptedData.length != 0) { 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); ASN1Primitive derObj = dis.readObject(); ASN1Sequence asn1 = (ASN1Sequence)derObj; ASN1Integer x = (ASN1Integer)asn1.getObjectAt(0); ASN1Integer y = (ASN1Integer)asn1.getObjectAt(1); org.bouncycastle.math.ec.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; } else { return null; } } else { return null; } } /** * 签名 * @param userId * @param privateKey * @param sourceData * @return * @throws IOException */ public static byte[] sign(byte[] userId, byte[] privateKey, byte[] sourceData) throws IOException { if (privateKey != null && privateKey.length != 0) { if (sourceData != null && sourceData.length != 0) { SM2 sm2 = SM2.Instance(); BigInteger userD = new BigInteger(privateKey); org.bouncycastle.math.ec.ECPoint userKey = sm2.ecc_point_g.multiply(userD); byte[] z = sm2.sm2GetZ(userId, userKey); SM3Digest sm3 = new SM3Digest(); sm3.update(z, 0, z.length); sm3.update(sourceData, 0, sourceData.length); byte[] md = new byte[32]; sm3.doFinal(md, 0); SM2Result sm2Result = new SM2Result(); sm2.sm2Sign(md, userD, userKey, sm2Result); 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); DERSequence sign = new DERSequence(v2); byte[] signdata = sign.getEncoded(); return signdata; } else { return null; } } else { return null; } } /** * 验签 * @param userId * @param publicKey * @param sourceData * @param signData * @return * @throws IOException */ public static boolean verifySign(byte[] userId, byte[] publicKey, byte[] sourceData, byte[] signData) throws IOException { if (publicKey != null && publicKey.length != 0) { if (sourceData != null && sourceData.length != 0) { SM2 sm2 = SM2.Instance(); org.bouncycastle.math.ec.ECPoint userKey = sm2.ecc_curve.decodePoint(publicKey); 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); ByteArrayInputStream bis = new ByteArrayInputStream(signData); ASN1InputStream dis = new ASN1InputStream(bis); ASN1Primitive derObj = dis.readObject(); Enumeration<ASN1Integer> e = ((ASN1Sequence)derObj).getObjects(); BigInteger r = ((ASN1Integer)e.nextElement()).getValue(); BigInteger s = ((ASN1Integer)e.nextElement()).getValue(); SM2Result sm2Result = new SM2Result(); sm2Result.r = r; sm2Result.s = s; sm2.sm2Verify(md, userKey, sm2Result.r, sm2Result.s, sm2Result); return sm2Result.r.equals(sm2Result.R); } else { return false; } } else { return false; } } public class MyKeyPair { String publicKey; String privateKey; public String getPublicKey() { return publicKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } } public static void main(String[] args) throws Exception { String plainText = "你好啊,朋友"; byte[] sourceData = plainText.getBytes(); System.out.println("原数据: " plainText); //1.生成密钥对 SM2Utils.MyKeyPair myKeyPair = new SM2Utils().generateKeyPair(); String privateKey = myKeyPair.getPrivateKey(); String publicKey = myKeyPair.getPublicKey(); //测试用户 String userId = "9001@qq.COM"; //签名 byte[] c = sign(userId.getBytes(), Util.hexToByte(privateKey), sourceData); System.out.println("SM2签名后值====" Util.getHexString(c)); //验签 boolean vs = verifySign(userId.getBytes(), Util.hexToByte(publicKey), sourceData, c); System.out.println("验签结果: " vs); //加密 byte[] cipherText = encrypt(Util.hexToByte(publicKey), sourceData); System.out.println("SM2加密后结果===" new String(Base64.encode(cipherText))); //解密 plainText = new String(decrypt(Util.hexToByte(privateKey), cipherText)); System.out.println("解密后获取的结果===" plainText); }}
评论