bouncycastle(BC)实现SM2国密加解密、签名、验签SM2国密加解密⼀个类就够了
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.65</version>
</dependency>
版本库经测试适⽤(1.61-1.68) 如有问题请留⾔纠正
本⽂参考博主「RisenMyth」:blog.csdn/RisenMyth/article/details/107212156
若要使⽤⽼版本的写法可以参考 blog.csdn/fenglongmiao/article/details/79501757
import org.GMNamedCurves;
import org.GMObjectIdentifiers;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.jcajce.BCECPrivateKey;
import org.bouncycastle.jcajce.BCECPublicKey;
import org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory;
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.ECPoint;
import org.ders.Hex;
import org.springframework.stereotype.Component;
pto.BadPaddingException;
pto.Cipher;
pto.IllegalBlockSizeException;
pto.NoSuchPaddingException;
import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.security.*;
import CertificateException;
import X509Certificate;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
/**
* bcprov-jdk15on 版本适⽤(1.61-1.68)
* @author dashou
* @date 2021-4-13
*/
@Component
public class SM2Util {
private BouncyCastleProvider provider;
// 获取SM2相关参数
private X9ECParameters parameters;
/
/ 椭圆曲线参数规格
private ECParameterSpec ecParameterSpec;
// 获取椭圆曲线KEY⽣成器
private KeyFactory keyFactory;
private SM2Util(){
try {
provider = new BouncyCastleProvider();
parameters = ByName("sm2p256v1");
ecParameterSpec = new Curve(),
keyFactory = Instance("EC", provider);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* SM2算法⽣成密钥对
*
* @return密钥对信息
*/
public KeyPair generateSm2KeyPair() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
// 获取⼀个椭圆曲线类型的密钥对⽣成器
final KeyPairGenerator kpg = Instance("EC", provider);
SecureRandom random = new SecureRandom();
// 使⽤SM2的算法区域初始化密钥⽣成器
kpg.initialize(sm2Spec, random);
// 获取密钥对
KeyPair keyPair = ateKeyPair();
return keyPair;
}
/**
* 加密
*
* @param input  待加密⽂本
* @param pubKey 公钥
* @return
*/
public String encode(String input, String pubKey)
throws NoSuchPaddingException, NoSuchAlgorithmException,
BadPaddingException, IllegalBlockSizeException,
InvalidKeySpecException, InvalidKeyException {
// 获取SM2相关参数
X9ECParameters parameters = ByName("sm2p256v1");
/
/ 椭圆曲线参数规格
ECParameterSpec ecParameterSpec = new Curve(), G(), N(), H());
// 将公钥HEX字符串转换为椭圆曲线对应的点
ECPoint ecPoint = Curve().decodePoint(Hex.decode(pubKey));
// 获取椭圆曲线KEY⽣成器
KeyFactory keyFactory = Instance("EC", provider);
BCECPublicKey key = (BCECPublicKey) atePublic(new ECPublicKeySpec(ecPoint, ecParameterSpec));
// 获取SM2加密器
Cipher cipher = Instance("SM2", provider);
// 初始化为加密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
// 加密并编码为base64格式
Encoder().encodeToString(cipher.Bytes()));
}
/**
* 解密
*
* @param input  待解密⽂本
* @param prvKey 私钥
* @return
*/
public byte[] decoder(String input, String prvKey) throws NoSuchPaddingException, NoSuchAlgorithmException,
InvalidKeySpecException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
// 获取SM2加密器
Cipher cipher = Instance("SM2", provider);
// 将私钥HEX字符串转换为X值
BigInteger bigInteger = new BigInteger(prvKey, 16);
BCECPrivateKey privateKey = (BCECPrivateKey) atePrivate(new ECPrivateKeySpec(bigInteger,
ecParameterSpec));
// 初始化为解密模式
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// 解密签名字符串是什么
return cipher.Decoder().decode(input));
}
/**
* 签名
*
* @param plainText 待签名⽂本
* @param prvKey    私钥
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws InvalidKeyException
* @throws SignatureException
*/
public String sign(String plainText, String prvKey) throws NoSuchAlgorithmException, InvalidKeySpecException,
InvalidKeyException, SignatureException {
// 创建签名对象
Signature signature = Instance(GMObjectIdentifiers.sm2sign_String(), provider);
// 将私钥HEX字符串转换为X值
BigInteger bigInteger = new BigInteger(prvKey, 16);
BCECPrivateKey privateKey = (BCECPrivateKey) atePrivate(new ECPrivateKeySpec
(bigInteger,
ecParameterSpec));
// 初始化为签名状态
signature.initSign(privateKey);
// 传⼊签名字节
signature.Bytes());
// 签名
Encoder().encodeToString(signature.sign());
}
public boolean verify(String plainText, String signatureValue, String pubKey) throws NoSuchAlgorithmException, InvalidKeySpecException,            InvalidKeyException, SignatureException {
// 创建签名对象
Signature signature = Instance(GMObjectIdentifiers.sm2sign_String(), provider);
// 将公钥HEX字符串转换为椭圆曲线对应的点
ECPoint ecPoint = Curve().decodePoint(Hex.decode(pubKey));
BCECPublicKey key = (BCECPublicKey) atePublic(new ECPublicKeySpec(ecPoint, ecParameterSpec));
// 初始化为验签状态
signature.initVerify(key);
signature.Bytes());
return signature.Decoder().decode(signatureValue));
}
/**
* 证书验签
*
* @param certStr      证书串
* @param plaintext    签名原⽂
* @param signValueStr 签名产⽣签名值此处的签名值实际上就是 R和S的sequence
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
public boolean certVerify(String certStr, String plaintext, String signValueStr)
throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateException {
byte[] signValue = Decoder().decode(signValueStr);
/*
* 解析证书
*/
CertificateFactory factory = new CertificateFactory();
X509Certificate certificate = (X509Certificate) factory
.engineGenerateCertificate(new Decoder().decode(certStr)));
// 验证签名
Signature signature = SigAlgName(), provider);
signature.initVerify(certificate);
signature.Bytes());
return signature.verify(signValue);
}
public static void main(String[] args) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
String str = "看看能不能⼀次通过";
SM2Util sm2 = new SM2Util();
KeyPair keyPair = ateSm2KeyPair();
BCECPrivateKey privateKey = (BCECPrivateKey) Private();
BCECPublicKey publicKey = (BCECPublicKey) Public();
// 拿到密钥
String pubKey = new Q().getEncoded(true)));
String prvKey = D().toString(16);
System.out.println("Private Key: " + prvKey);
System.out.println("Public Key: " + pubKey);
// 加解密测试
try {
System.out.println("加密前:" + str);
String encode = de(str, pubKey);
System.out.println("加密后:" + encode);
String decoder = new String(sm2.decoder(encode, prvKey));
System.out.println("解密后:" + decoder);
} catch (Exception e) {
System.out.println("加解密测试错误");
}
// 签名和验签测试
try {
System.out.println("签名源数据:" + str);
String signStr = sm2.sign(str, prvKey);
System.out.println("签名后数据:" + signStr);
boolean verify = sm2.verify(str, signStr, pubKey);
System.out.println("签名验证结果:" + verify);
} catch (Exception e) {
System.out.println("签名和验签测试错误");
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。