国密算法是国家密码局制定标准的一系列算法,包括SM1、SM2、SM3、SM4等。其中,SM1是采用硬件实现的,不予讨论;SM2是非对称加密算法;SM3是摘要算法;SM4是对称加密算法。本篇贴出SM2 Java版本实现生成公私钥及加解密、签名验签代码,供大家一起讨论学习,所有的代码实现都是基于BC库来做的。
BC库是实现加解密算法的基础库,我们首先要在代码里引入BC库
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.69</version>
</dependency>
下面是整个工具类,实现密钥生成,加解密及签名验签功能
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.signers.SM2Signer;
import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Sm2Utils {
private static Logger log = LoggerFactory.getLogger(Sm2Utils.class);
/**
* SM2算法生成密钥对
*
* @return 密钥对信息
*/
public static KeyPair generateSm2KeyPair() {
try {
final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("prime256v1");
final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
SecureRandom random = new SecureRandom();
kpg.initialize(sm2Spec, random);
KeyPair keyPair = kpg.generateKeyPair();
return keyPair;
} catch (Exception e) {
log.error("generate sm2 key pail failed:", e.getMessage(), e);
throw new RuntimeException("生成密钥对失败");
}
}
/**
* sm2公钥加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
KeySpec keySpec = new X509EncodedKeySpec(key);
PublicKey publicKey = KeyFactory.getInstance("EC", new BouncyCastleProvider()).generatePublic(keySpec);
ECPublicKeyParameters parameters = (ECPublicKeyParameters) ECUtil.generatePublicKeyParameter(publicKey);
CipherParameters pubKeyParameters = new ParametersWithRandom(parameters);
SM2Engine engine = new SM2Engine(SM2Engine.Mode.C1C2C3);
engine.init(true, pubKeyParameters);
return engine.processBlock(data, 0, data.length);
}
/**
* sm2私钥解密
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
KeySpec keySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyfactory = KeyFactory.getInstance("EC", new BouncyCastleProvider());
PrivateKey privateKey = keyfactory.generatePrivate(keySpec);
CipherParameters privateKeyParameters = ECUtil.generatePrivateKeyParameter(privateKey);
SM2Engine engine = new SM2Engine(SM2Engine.Mode.C1C2C3);
engine.init(false, privateKeyParameters);
byte[] byteDate = engine.processBlock(data, 0, data.length);
return byteDate;
}
/**
* 私钥签名
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] sign(byte[] data, byte[] key) throws Exception {
SM2Signer signer = new SM2Signer();
KeySpec keySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyfactory = KeyFactory.getInstance("EC", new BouncyCastleProvider());
PrivateKey privateKey = keyfactory.generatePrivate(keySpec);
ECPrivateKeyParameters keyParameters = (ECPrivateKeyParameters) ECUtil.generatePrivateKeyParameter(privateKey);
CipherParameters param = new ParametersWithRandom(keyParameters);
signer.init(true, param);
signer.update(data, 0, data.length);
return signer.generateSignature();
}
/**
* 公钥验签
* @param data
* @param sign
* @param key
* @return
* @throws Exception
*/
public static boolean verify(byte[] data, byte[] sign, byte[] key) throws Exception {
SM2Signer signer = new SM2Signer();
KeySpec keySpec = new X509EncodedKeySpec(key);
PublicKey publicKey = KeyFactory.getInstance("EC", new BouncyCastleProvider()).generatePublic(keySpec);
CipherParameters param = ECUtil.generatePublicKeyParameter(publicKey);
signer.init(false, param);
signer.update(data, 0, data.length);
return signer.verifySignature(sign);
}
public static void main(String[] args) throws Exception {
KeyPair keyPair = generateSm2KeyPair();//生成密钥
String publicKey = Base64.encodeBase64String(keyPair.getPublic().getEncoded());
String privateKey = Base64.encodeBase64String(keyPair.getPrivate().getEncoded());
System.out.println("sm2公钥=" + publicKey);
System.out.println("sm2私钥=" + privateKey);
String plaintext = "test";//明文
String signature = Base64.encodeBase64String((sign(plaintext.getBytes("utf-8"),keyPair.getPrivate().getEncoded())));
String ciphertext = Base64.encodeBase64String(encrypt(plaintext.getBytes("utf-8"), Base64.decodeBase64(publicKey)));
System.out.println("ciphertext: " + ciphertext);
System.out.println("signature: " + signature);
boolean result = verify(plaintext.getBytes("utf-8"),Base64.decodeBase64(signature),keyPair.getPublic().getEncoded());
plaintext = new String(decrypt(Base64.decodeBase64(ciphertext), Base64.decodeBase64(privateKey)), "utf-8");
System.out.println("plaintext: " + plaintext);
System.out.println("verify result: " + result);
}
}