Reading an X.509 certificate with Java(使用 Java 读取 X.509 证书)
问题描述
我正在尝试使用 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);
这篇关于使用 Java 读取 X.509 证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Java 读取 X.509 证书
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01