简体   繁体   中英

How to read a PEM certificate without BEGIN and END via PEMParser in Java using BouncyCastle

I have a cert.PEM file which I created in this way:

Base64 encoder = new Base64();
File file = new File(certPath + "cert.pem");
file.createNewFile();
writer = new FileWriter(file);
writer.write(new String(encoder.encode(cert.getEncoded())));
writer.close();

It is without ----BEGIN CERTIFICATE---- and -----END CERTIFICATE----- parts. It is in its raw form like:

MIIDRjCCAi6gAwIBAgIE4B5BgzANBgkqhkiG9w0BAQsFADBlMRkwFwYDVQQDDBBBbGlyZXphIE1vaGFtYWRpMRMwEQYDVQQKDApTdU5vdmEgTExQMQ0wCwYDVQQGEwRJcmFuMRMwEQYDVQQFEwotNTM0ODg4MDYxMQ8wDQYDVQQFEwZTdU5vdmEwHhcNMTYwNTMxMTE0MDQyWhcNMTYwNjE3MTIyMTExWjBlMRkwFwYDVQQDDBBBbGlyZXphIE1vaGFtYWRpMRMwEQYDVQQKDApTdU5vdmEgTExQMQ0wCwYDVQQGEwRJcmFuMRMwEQYDVQQFEwotNTM0ODg4MDYxMQ8wDQYDVQQFEwZTdU5vdmEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCOEiLfrO9B2Cr1kEJ3rkI4FSaZMhG8FVPz+JuMxA/OhUNiy3c1/WTNu2tYudld8vowq6kKHxwERcCxLVR3b5ua3dlprTGo4CJSMlF7g6rjSOLmfA52385QfXBbRg+2N02EBTABufH0I+039bWVDDuk2c7tLcpfiK4YHt2f+C1/SzerYwxHIqPT1NxT/NC4SudeaUVljxQa9DRy+WRk/T8ifaphxoqlCcMMPa42+OBLeER3fcTep872hL5IsgWtxU6q5tRbENIXlWyeLQuva02APXyrOI9IssetKIy1Oagp0ji6rWdmHfmGZqBsspWBNio02kZZwSa6DvMHWQdgXn23AgMBAAEwDQYJKoZIhvcNAQELBQADggEBAHAZYqAS0lcZvDMubimsdzF9RkC0gaombd9sM71lhw/Ad6Czv27KTyeY8Y1uBgYqJ5DTREJEBuHbgBdryjhDEdSo+d1wNqws3krLC3qv0jWD4sVhTv1AyNAmkFTJmea0aROaTZrkw+o5cerPKCEBabP7eFQSHu1b8d8xE/xr9os73sI8nBGoOzT87OE/4JQhg733xJh1xENmnrYTsadpOx+8l35RIIzFhag4BdNIlMc/S+bowR5m8iePTaYvb9TZAi4yetj4nWuLnm7nAyqL8idSh2R8esjEk3Y27r7PfJC3p51shlcgJ5Sh/uCNc1P5Bea8mRrX0KE+K1QxEwTjIAw=

Now I want to read it again and parse it to a X509CertificateHolder by this code:

PEMParser r = new PEMParser(new FileReader(certFile));
            System.out.println(r.ready());
            PemObject object = r.readPemObject();
            X509CertificateHolder cert = new X509CertificateHolder(object.getContent());
            Date date = new Date();
            if (date.compareTo(cert.getNotAfter()) > 0)
            {
                generateCert();
            }

and I get this:

java.lang.NullPointerException
    at com.sunova.bot.Launcher.<init>(Launcher.java:67)
    at com.sunova.bot.Launcher.getInstance(Launcher.java:41)
    at com.sunova.bot.Launcher.main(Launcher.java:48)

which is due to r.readPemObject() returns null. What should I do?

The PEM format includes the BEGIN CERTIFICATE and END CERTIFICATE headers. See http://tools.ietf.org/html/rfc7468#page-11 . So you should add them in your .pem file. After this, PEMParser will work properly

If you can not do this, add the headers on the fly before providing the content to PEMParser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM