Write x509 certificate into PEM formatted string in java?

后端 未结 10 2299
天涯浪人
天涯浪人 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:06

    Haven't seen anyone bring up Java 8's Base64.getMimeEncoder method yet - actually allows you to specify both the line length and line separator like so:

    final Base64.Encoder encoder = Base64.getMimeEncoder(64, LINE_SEPARATOR.getBytes());
    

    I looked to see if there was any difference with this ^ vs the standard encoder, and I couldn't find anything. The javadoc cites RFC 2045 for both BASIC and MIME encoders, with the addition of RFC 4648 for BASIC. AFAIK both of these standards use the same Base64 alphabet (tables look the same), so you should fine to use MIME if you need to specify a line length.

    This means that with Java 8, this can be accomplished with:

    import java.security.cert.Certificate;
    import java.security.cert.CertificateEncodingException;
    import java.util.Base64;
    

    ...

    public static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
    public static final String END_CERT = "-----END CERTIFICATE-----";
    public final static String LINE_SEPARATOR = System.getProperty("line.separator");
    

    ...

    public static String formatCrtFileContents(final Certificate certificate) throws CertificateEncodingException {
        final Base64.Encoder encoder = Base64.getMimeEncoder(64, LINE_SEPARATOR.getBytes());
    
        final byte[] rawCrtText = certificate.getEncoded();
        final String encodedCertText = new String(encoder.encode(rawCrtText));
        final String prettified_cert = BEGIN_CERT + LINE_SEPARATOR + encodedCertText + LINE_SEPARATOR + END_CERT;
        return prettified_cert;
    }
    

提交回复
热议问题