本文主要是介绍keyStore类处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
加载公钥证书, 成为keyStore
public static void main(String[] args) {Security.addProvider(new BouncyCastleProvider());String certFilePath = "C:\\alipayRootCert.crt";String certType = "X.509";String provider = "BC";try (FileInputStream fis = new FileInputStream(certFilePath)) {CertificateFactory certFactory = CertificateFactory.getInstance(certType, provider);Collection<? extends Certificate> certs = certFactory.generateCertificates(fis);// 遍历所有证书int aliasCounter = 1;KeyStore keyStore = KeyStore.getInstance("JKS");keyStore.load(null, null); // 加载一个空的KeyStorefor (Certificate cert : certs) {// 这里可以处理每个证书,例如打印信息或添加到KeyStore(如果需要)String alias = "alias_" + aliasCounter++;// 如果你需要将证书添加到KeyStore,你需要为每个证书创建一个唯一的别名keyStore.setCertificateEntry(alias, cert);}String value = CertUtils.getX509CertContent(keyStore);System.out.println(value);} catch (Exception e) {}
}
keyStore对象返回公钥证书的原始内容
public static String getX509CertContent(KeyStore keyStore) {StringBuilder certContentBuilder = new StringBuilder();try {// 获取KeyStore中的证书Enumeration<String> aliases = keyStore.aliases();while (aliases.hasMoreElements()) {String alias = aliases.nextElement();if (keyStore.isCertificateEntry(alias)) {// 获取证书Certificate certificate = keyStore.getCertificate(alias);byte[] encodedCert = certificate.getEncoded();byte[] bytes = Base64.encodeBase64(encodedCert);// 将证书内容转换为Base64字符串String certContentBase64 = new String(bytes);// 获取证书的原始内容String certContent = String.format("-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n",certContentBase64.replaceAll("(.{64})", "$0\n") // 为了可读性,在PEM编码中,Base64编码的文本被分成多行,每行通常包含64个字符。);certContentBuilder.append(certContent);}}} catch (Exception e) {log.error("getX509CertContent error, {}", e.getMessage(), e);}return certContentBuilder.toString();}
这篇关于keyStore类处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!