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.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Previous answer gives compatibility problems with 3de party software (like PHP), because PEM cert is not correctly chunked.
Imports:
Code:
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:
Code:
(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: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,
If you use BouncyCastle, you can use PEMWriter class to write out X509 certificate in PEM.
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: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:
...
...
To build on ZZ Coder's idea, but without using the
sun.misc
classes that aren't guaranteed to be consistent between JRE versions, consider thisUse Class:
Code:
Yet another alternative for encoding using Guava's BaseEncoding:
And then: