How to load public certificate from pem file?

江枫思渺然 提交于 2019-11-30 02:00:08
dave_thompson_085

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