Write x509 certificate into PEM formatted string i

2019-01-21 08:51发布

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 base 64 encoding it and appending the header and footer to create a PEM string, but it seems bad. Especially since I have to throw in line breaks too.

标签: java x509 pem der
8条回答
Explosion°爆炸
2楼-- · 2019-01-21 09:50

In BouncyCastle 1.60 PEMWriter has been deprecated in favour of PemWriter.

StringWriter sw = new StringWriter();

try (PemWriter pw = new PemWriter(sw)) {
  PemObjectGenerator gen = new JcaMiscPEMGenerator(cert);
  pw.writeObject(gen);
}

return sw.toString();

PemWriter is buffered so you do need to flush/close it before accessing the writer that it was constructed with.

查看更多
走好不送
3楼-- · 2019-01-21 09:56

If you have PEMWriter from bouncy castle, then you can do the following :

Imports :

import org.bouncycastle.openssl.PEMWriter;

Code :

/**
 * Converts a {@link X509Certificate} instance into a Base-64 encoded string (PEM format).
 *
 * @param x509Cert A X509 Certificate instance
 * @return PEM formatted String
 * @throws CertificateEncodingException
 */
public String convertToBase64PEMString(Certificate x509Cert) throws IOException {
    StringWriter sw = new StringWriter();
    try (PEMWriter pw = new PEMWriter(sw)) {
        pw.writeObject(x509Cert);
    }
    return sw.toString();
}
查看更多
登录 后发表回答