使用 Java 读取 X.509 证书

2022-01-25 00:00:00 saml certificate java

我正在尝试使用 Java 读取我从外部方收到的证书.代码抛出以下错误:

I am trying to use Java to read a certificate that I received from an external party. The code is throwing the following error:

java.lang.RuntimeException: java.security.cert.CertificateException: Unable to initialize, java.io.IOException: extra data given to DerValue constructor

java.lang.RuntimeException: java.security.cert.CertificateException: Unable to initialize, java.io.IOException: extra data given to DerValue constructor

代码:

FileInputStream ksfis = new FileInputStream(this.getCertificateFile());
ksbufin = new BufferedInputStream(ksfis);
certificate = (X509Certificate)
  CertificateFactory.getInstance("X.509").generateCertificate(ksbufin);

为了确保问题不在代码中,我创建了一个自签名证书并将其与代码一起使用,它运行良好.我已经在系统密钥链中安装了这两个证书,它们都是有效的.我使用的是 Mac 和 Java 1.6.

To make sure the problem was not in the code, I created a self-signed certificate and used it with the code, and it worked fine. I have installed both certificates in the system key chain, and they both are valid. I am using a Mac and Java 1.6.

知道为什么在加载外部方证书时会出现上述异常吗?您认为它在传输过程中损坏了吗?如果是这样,它应该不会在本地系统上显示为有效,对吧?

Any idea why I get the above exception when I load the external Party certificate? Do you think it got corrupted during transfer? If it did, it should not show up as valid on the local system, right?

推荐答案

尝试使用openssl输入这个,然后导入结果:

Try to type this using openssl, and then import the result:

openssl x509 -outform der -in certificate.pem -out certificate.der

或在轻量级 API 中使用 Java Bouncy Castle 功能:

or use the Java Bouncy Castle functionality in the lightweight API:

http://www.bouncycastle.org/docs/pkixdocs1.5on/org/bouncycastle/openssl/PEMReader.html

您可以再次对结果进行编码,然后使用 Java 中的 X509" CertificateBuilder 来获取 JCE 定义的证书,例如

You may encode the result again and then use the "X509" CertificateBuilder in Java to get a JCE defined certificate, e.g.

ByteArrayInputStream certStream  =  new ByteArrayInputStream(binaryCert);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certStream);

相关文章