Reading an X.509 certificate with Java

Deadly 提交于 2019-12-17 19:21:53

问题


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

The code:

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

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?


回答1:


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

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

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

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

You may encode the result again and then use the default CertificateBuilder in Java to get a JCE defined certificate.



来源:https://stackoverflow.com/questions/11621414/reading-an-x-509-certificate-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!