How to load public certificate from pem file? How to load public certificate from pem file? java java

How to load public certificate from pem file?


An X.509 certificate and an X509EncodedKeySpec are quite different structures, and trying to parse a cert as a key won't work.Java's X509EncodedKeySpec is actually SubjectPublicKeyInfo from X.509 or equivalent and more convenient PKIX also linked from Key, which is only a small part of a certificate.

What you need to do is read and parse the cert and then extract the pubkey from the cert.Standard SunJCE CertificateFactory can do it(and can read either PEM or DER to boot) like this:

CertificateFactory fact = CertificateFactory.getInstance("X.509");FileInputStream is = new FileInputStream (args[0]);X509Certificate cer = (X509Certificate) fact.generateCertificate(is);PublicKey key = cer.getPublicKey();is.close();// add error handling as appropriate, try-with-resources is often good

If you have BouncyCastle you can use its provider the same way (just add a second argument to .getInstance or set the default provider list order), or you can use PEMParser with JcaX509CertificateConverter -- which effectively does the same thing, internally running the data through a CertificateFactory.


With Sun JVM it is also possible with

import java.security.cert.X509Certificate;import sun.security.x509.X509CertImpl;InputStream is = ...X509Certificate crt = new X509CertImpl(is);

, although I'd prefer the accepted answer as JVM implementation-independent one.

Under the hood, in Sun JVM, CertificateFactory(more precisely, X509Factory) does instantiate X509CertImpl , but there is very subtle difference between the two approaches: CertificateFactory caches X509 Certificate instances by binary content of the input stream, the one that can be retrieved by cer.getEncoded().

The cache can be cleared by

fact.generateCertificate(null);