Write x509 certificate into PEM formatted string in java?

后端 未结 10 2315
天涯浪人
天涯浪人 2020-12-07 15:48

Is there some high level way to write an X509Certificate into a PEM formatted string? Currently I\'m doing x509cert.encode() to write it into a DER formatted string, then ba

10条回答
  •  清歌不尽
    2020-12-07 16:11

    The following uses no big external libraries or possibly version-inconsistent sun.* libraries. It builds on judoman's answer, but it also chunks lines at 64 characters, as required by OpenSSL, Java, and others.

    Import:

    import javax.xml.bind.DatatypeConverter;
    import java.security.cert.X509Certificate;
    import java.io.StringWriter;
    

    Code:

    public static String certToString(X509Certificate cert) {
        StringWriter sw = new StringWriter();
        try {
            sw.write("-----BEGIN CERTIFICATE-----\n");
            sw.write(DatatypeConverter.printBase64Binary(cert.getEncoded()).replaceAll("(.{64})", "$1\n"));
            sw.write("\n-----END CERTIFICATE-----\n");
        } catch (CertificateEncodingException e) {
            e.printStackTrace();
        }
        return sw.toString();
    }
    

    (I would have just commented on judoman's answer, but I don't have enough reputation points to be allowed to comment, and my simple edit was rejected because it should have been a comment or an answer, so here's the answer.)

    If you want to write straight to file, also import java.io.FileWriter and:

    FileWriter fw = new FileWriter(certFilePath);
    fw.write(certToString(myCert));
    fw.close();
    

提交回复
热议问题