如何使用BouncyCastle在Java中通过PEMParser读取没有BEGIN和END的PEM证书

时间:2016-05-31 12:00:23

标签: java x509certificate bouncycastle x509 pem

我有一个cert.PEM文件,我以这种方式创建:

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();

没有----BEGIN CERTIFICATE---------END CERTIFICATE-----部分。它的原始形式如下:

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

现在我想再次阅读它,并通过以下代码将其解析为X509CertificateHolder

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();
            }

我得到了这个:

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)
r.readPemObject()引起的

返回null。我该怎么办?

1 个答案:

答案 0 :(得分:0)

PEM格式包括BEGIN CERTIFICATE和END CERTIFICATE标题。见http://tools.ietf.org/html/rfc7468#page-11。所以你应该在.pem文件中添加它们。在此之后,PEMParser将正常工作

如果您无法执行此操作,请在向PEMParser提供内容之前动态添加标题