Skip to content
Advertisement

How to load public certificate from pem file?

I was trying to extract RES public key from the file below

JavaScript

Here is the code i did..

JavaScript

But It throws out

java.security.InvalidKeyException: IOException: ObjectIdentifier() — data isn’t an object ID

What’s the appropriate way to extract RES Public key from a file..

Advertisement

Answer

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement