Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an X509Certicate from a DER decoded String

I have a X509Certificate and I write/print it to a file as follows. (I'm not writing encoded bytes, because I want to read the content of the certicate)

X509Certificate cer = generateCertificate(); // cer is DER encoded
writeToFile( cer.toString() ); // cer.toString() converts DER to UTF/ASCII???

Later I want to read this file (above) as String and create a new X509Certificate.

String cerStr = readCerFromFile(); // Read what is written above. In ASCII/ UTF format
ByteArrayInputStream bais = null;
try {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    bais = new ByteArrayInputStream(cerStr.getBytes());
    return (X509Certificate) cf.generateCertificate(bais);
} ...

This throws following Exception.

Java.security.cert.CertificateParsingException: Invalid DER-encoded certificate data

And it is obvious that I'm not converting cerStr to DER format (and I don't know whether it is possible to convert into DER ). Can any one please explain how can create an X509Certicate from a String which is not encoded.

Thanks in advance.!

like image 524
Fahim Avatar asked Jul 13 '12 05:07

Fahim


2 Answers

The short answer: you cannot. DER encodes too many details that cannot be easily converted to and back from a String. You are better off simply saving the DER encoded certificate using cer.getEncoded() as GregS has explained in the comments.

If you want to see the the contents of the certificate, simply save it with a file extension that your operating system recognizes and double click it. If you want to have a command line method of printing the plain text information use e.g. openssl:

openssl x509 -text -noout -inform DER -in mycertificate.crt

Which is standard included or optional in many Unix flavours (Linux, Apple) and can be run on Windows as well.

like image 123
Maarten Bodewes Avatar answered Nov 10 '22 19:11

Maarten Bodewes


When you take certificate as raw data cert.getEncoded() (in .Net it is cert.RawData) it is encoded in DER format. Informally speaking it is just a special binary representation of the certificate.

But there exists good string representation of certificate. You can convert raw representation of certificate in DER to Base64 formatted string. I don't know JAVA, so in .Net it will look like this Convert.ToBase64dString(cert.RawData).

You can save certificate in both formats to a file with .cer or .crt extension and open it using standart OS certificate viewer.

like image 43
Sergio Rykov Avatar answered Nov 10 '22 19:11

Sergio Rykov