实例介绍
【实例简介】由于很多同学想做伸手党,此处重新上传了一个完整版的代码。包含了生成随机秘钥对,数据加密,数据解密,签名与验签例子,并给出了使用姿势。使用者需要使用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);
}
}
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论