java - 如何在一个crt文件中导出多个公共(public)证书

标签 java private x509certificate keystore public

我有一个 keystore.jks 文件,其中包含多个证书,包括公钥和私钥。 现在我想知道如何将所有公钥证书导出到新文件 all-public-cert.crt 文件中。

此“all-public-cert.crt”文件仅包含证书(仅公钥)。此文件中不应包含任何私钥。

此后,我想通过java代码准备好这个“all-public-cert.crt”文件,并使用质询响应验证公钥和私钥。

请指导我或建议我一些引用文档或网址。

注意:我可以使用任何工具,例如 openssl 或 keytool。

谢谢和问候, 高拉夫·帕利瓦尔

最佳答案

通常是 keystore ,即您的 keystore.jks 包含私钥和相应的 X.509 证书。但 X.509 证书不包含私钥,正如您错误地假设的那样:

I have a keystore.jks file with multiple certificate including public and private key

This "all-public-cert.crt" file contain only certificate (public key only) . should not contain any private key in this file.

这意味着您的 X.509 证书仅包含公钥信息,不包含私钥信息。

为了从您的 keystore 获取证书(将错误处理放在一边):

String keystorePath = ....
InputStream is = new FileInputStream(new File(keystorePath));
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, "keystorePassword".toCharArray());

Enumeration e = ks.aliases();
Set<Certificate> certs = new HashSet<Certificate>();
while (e.hasMoreElements()) {
  Certificate cert = ks.getCertificate((String) enumeration.nextElement());
  certs.add(cert);
}

现在您的certs集中已拥有所有证书。但为什么需要将它们全部放入 all-public-cert.crt 中。

1.) 首先,您不能将多个证书放入一个文件中,并希望该一个文件可以以“正常”方式使用(例如双击打开它,将其导入其他应用程序,..)。该文件将是垃圾文件,只能从您的应用程序中读取

2.) 因此,文件扩展名不应为 .crt,而应为 .myExportedCertificates 或类似名称。

我认为您只想将证书存储在文件系统上以便以后使用它们。在这种情况下,只需使用此代码(错误处理是您的工作):

String pathToStoreTheCerts = ...
File path = new File(pathToStoreTheCerts);
OutputStream os = null;
for (X509Certificate cert : certs) {
  File certFile = new File(path, cert.getSubjectX500Principal().getName() + ".crt");
  os = new FileOutputStream(certFile);
  os.write(cert.getEncoded());
  os.flush();
}
os.close();

关于java - 如何在一个crt文件中导出多个公共(public)证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24695195/

相关文章:

java - JMS onMessage() 和并发

encryption - 无法为新用户生成有效的 ssh 公钥/私钥对

java - 如何在 TrustManager 的 checkServerTrusted() 中获取 CertPathValidatorResult?

c# - 收到的 WCF 服务器证书的部分链验证失败

azure - 将证书添加到 Azure 应用服务以调用外部 API

Java找不到符号symbol : method getFiles()

java - Weblogic11g 中 Reflecions 0.9.9-RC1 的类加载器错误

Java ByteBuffer 性能问题

java - 父类中的私有(private)字段被子类隐藏/隐藏 - 检查以捕获它

Firefox 8 隐私浏览中的 Javascript 加速?