pizzathehut pizzathehut - 9 months ago 89
Java Question

Write x509 certificate into PEM formatted string in java?

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.

Answer Source

This is not bad. Java doesn't provide any functions to write PEM files. What you are doing is the correct way. Even KeyTool does the same thing,

BASE64Encoder encoder = new BASE64Encoder();
encoder.encodeBuffer(cert.getEncoded(), out);

If you use BouncyCastle, you can use PEMWriter class to write out X509 certificate in PEM.