How to load public certificate from pem file?

后端 未结 1 2000
眼角桃花
眼角桃花 2020-12-13 13:17

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

-----BEGIN CERTIFICATE-----
MIIGwTCCBamgAwIBAgIQDlV4zznmQiVeF45Ipc0k7DANBgkqhkiG9w0BAQUFADBmMQswCQ         


        
相关标签:
1条回答
  • 2020-12-13 13:54

    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();
    
    0 讨论(0)
提交回复
热议问题