I was trying to extract RES public key from the file below
-----BEGIN CERTIFICATE-----
MIIGwTCCBamgAwIBAgIQDlV4zznmQiVeF45Ipc0k7DANBgkqhkiG9w0BAQUFADBmMQswCQ
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 X.509's SubjectPublicKeyInfo, which is 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.
I don't know the BC way to do this, but standard SunJCE CertificateFactory
can do it
(and can read either PEM or DER to boot) like this (adjust error cleanup and error handling to taste):
CertificateFactory fact = CertificateFactory.getInstance("X.509");
FileInputStream is = new FileInputStream (args[0]);
X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
PublicKey key = cer.getPublicKey();