private void createPfxCert() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, IOException, CertificateException, InvalidKeySpecException, KeyStoreException {
String keyType = "RSA";//密钥算法
String certPassword = "111111";//证书密码
String commonName = "某某测试设备证书";//公司名称
String ucsCode = "ait1234567890";//公司社会信用码
String duration = "1";//证书有效期 单位为:月
KeyPair keyPair = KeyUtils.generateKeyPair(keyType.toLowerCase());
String dn = "CN="+commonName + ",OU="+ucsCode+",C=CN";
PKCS10CertificationRequest pkcs10CertificationRequest = CertUtils.generateCSR(new X500Name(dn), keyPair.getPublic(), keyPair.getPrivate());
String p10= Base64.encodeBytes(pkcs10CertificationRequest.getEncoded());
JSONObject certResult = applySemiCert(p10,commonName,ucsCode,duration);//申请证书
//log.info("certResult==="+certResult.toJSONString());
String errorCode = certResult.getString("errorCode");
if (StringUtils.equals("0", errorCode)) {
JSONObject certInfo = certResult.getJSONObject("certInfo");
String cert = certInfo.getString("cert");
//String serialNumber = certInfo.getString("serialNumber");
X509Certificate pubKey = new JcaX509CertificateConverter().setProvider("BC")
.getCertificate(new X509CertificateHolder(Base64.decode(cert)));
String privateKeyStr = Base64.encodeBytes(keyPair.getPrivate().getEncoded());
byte[] privateKeyBytes = Base64.decode(privateKeyStr);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
// 创建KeyStore,存储证书ca
Security.insertProviderAt(new BouncyCastleProvider(), 1);
//KeyStore store = KeyStore.getInstance("BKS", "BC");
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(null, null);
store.setKeyEntry("pc", privateKey,
certPassword.toCharArray(), new Certificate[]{pubKey});
String outPath = "D:\\"+commonName+".pfx";
OutputStream outputStream = new FileOutputStream(outPath);
store.store(outputStream, certPassword.toCharArray());
} else {
throw new RuntimeException("error");
}
}
关键点,获取到cert后的代码部分,把公钥和私钥及密码存储到一个文件中。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/142687.html