简体   繁体   English

从 .cer 证书导出证书链

[英]Export certificate chain from .cer certificate

I have .cer certificate.我有 .cer 证书。 When I'm opening it, it shows me certificate chain.当我打开它时,它会显示证书链。

点击显示图片

Using this code, I read the certificate to x509certificate file.使用此代码,我将证书读取到 x509certificate 文件。

File certificateFile = new File("C:\\Users\\grish\\Desktop\\certificateForValidation.cer");
        InputStream inputStream = new FileInputStream(certificateFile);

        X509Certificate certificate = new X509CertImpl(inputStream);

I want to get certificate chain from that file !我想从那个文件中获取证书链! (end-entity, CA, Root) How can I do that programmatically in java. (end-entity, CA, Root) 我怎样才能在 java 中以编程方式做到这一点。

With C#, this is much more easy使用 C#,这更容易

X509Chain ch = new X509Chain();
ch.ChainPolicy.RevocationMode = X509RevocationMode.Online;
ch.Build (certificate);

And then I can get all certificates from ch.然后我可以从 ch 获取所有证书。

First of all make sure you are using the java.security.cert package;首先确保您使用的是java.security.cert包; see JDK 17 API doc for java.security.cert .请参阅java.security.cert 的 JDK 17 API 文档

Avoid using javax.security.cert .避免使用javax.security.cert The package is marked as deprecated an will be removed in future releases;该软件包被标记为已弃用,并将在未来版本中删除; see JDK 17 API doc for javax.security.cert .请参阅javax.security.cert 的 JDK 17 API 文档

The following code will return a collection of java.security.cert.X509Certificate objects.以下代码将返回java.security.cert.X509Certificate对象的集合。 In the case of your example with the certificate of medium.com the list will contain three items;在您的示例中,证书为 medium.com 的情况下,列表将包含三个项目; one for every certificate in the chain.链中的每个证书对应一个。

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.List;

public static void main(String[] args) {
    try (InputStream inStream = new FileInputStream("C:\\Users\\grish\\Desktop\\Coding Space\\Certificates\\certificateForValidation.p7b")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        List<X509Certificate> certs = (List<X509Certificate>) cf.generateCertificates(inStream);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

I tested it with a PEM formated chain but it should work with PCKS#7 (.p7b file extension) as well;我使用 PEM 格式的链对其进行了测试,但它也应该适用于 PCKS#7(.p7b 文件扩展名); see the documentation of the generateCertificates(InputStream inStream) method.请参阅generateCertificates(InputStream inStream)方法的文档

Find more information about x.509 encoding and conversion here 在此处查找有关 x.509 编码和转换的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM