openssl 1.1.1 某个版本是支持sm2算法的,
运行
openssl ecparam -list_curves | grep SM2
返回
SM2 : SM2 curve over a 256 bit prime field
说明支持
1 生成SM2格式pri.key私钥
openssl ecparam -genkey -name SM2 -out pri.key
2
根据pri.key
生成请求ca-req.csr
openssl req -new -out ca-req.csr -key pri.key
输入各种字段
3 生成公钥证书
openssl x509 -req -in ca-req.csr -out ca-cert.pem -signkey pri.key -days 3650
注意一定要是x509格式的,否则java的bc无法读取
4 生成pfx文件
openssl pkcs12 -export -clcerts -in ca-cert.pem -inkey pri.key -out cert.pfx
5 将私钥转为pem格式
openssl ec -in pri.key -out pri.pem
读取私钥的java代码
-
package test;
-
-
import org.bouncycastle.cert.CertException;
-
import org.bouncycastle.jce.provider.BouncyCastleProvider;
-
import org.bouncycastle.openssl.PEMKeyPair;
-
import org.bouncycastle.openssl.PEMParser;
-
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
-
-
import java.io.FileInputStream;
-
import java.io.InputStreamReader;
-
import java.security.PrivateKey;
-
import java.security.Security;
-
-
public class SM2Private {
-
public static PrivateKey readPrivateKeyPem(String privateKeyPemPath) throws CertException {
-
try {
-
PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(privateKeyPemPath)));
-
Object readObject = pemParser.readObject();
-
if (readObject instanceof PEMKeyPair) {
-
PEMKeyPair key = (PEMKeyPair) readObject;
-
return new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getKeyPair(key)
-
.getPrivate();
-
}
-
throw new CertException("read privateKey failed");
-
} catch (Exception e) {
-
throw new CertException("read privateKey failed", e);
-
}
-
}
-
public static void main(String[] args) throws CertException {
-
Security.addProvider(new BouncyCastleProvider());
-
PrivateKey privateKey = SM2Private.readPrivateKeyPem("d:/pki/pri.pem");
-
System.out.println(privateKey);
-
-
}
-
-
}
读取公钥的java代码
-
Security.addProvider(new BouncyCastleProvider());
-
-
/**
-
* TODO
-
* 服务端验签代码,整体认证方案为挑战应答模式
-
* 1.后端生产随机数发送前端。
-
* 2.前端对随机数进行签名,并发送后端。
-
* 3.后端收到签名值结合随机数进行验签完成认证流程。
-
*/
-
//用户公钥,从证书中获取
-
PublicKey publicKey = null;
-
-
try {
-
byte[] key = Files.readAllBytes(Paths.get("D:\\pki", "ca-cert.pem"));
-
-
Security.addProvider(new BouncyCastleProvider());
-
-
final PemObject pemObject;
-
-
try (PemReader pemReader = new PemReader(new InputStreamReader(
-
new ByteArrayInputStream(key)))) {
-
pemObject = pemReader.readPemObject();
-
}
-
byte[] decoded = pemObject.getContent();
-
CertificateFactory cf =
-
CertificateFactory.getInstance("X.509", "BC");
-
InputStream inputStream = new ByteArrayInputStream(decoded);
-
Certificate certificate = cf.generateCertificate(inputStream);
-
publicKey = certificate.getPublicKey();
-
-
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
阅读(4048) | 评论(0) | 转发(0) |