0

I am trying to detect the content of a PEM file. In case it contains certificate infos, the following code is perfect to get X509Certificates informations:

X509Certificate cert = X509CertUtils.parse(Files.readAllBytes(file.toPath()));

but returns NULL of course if it's a key instead of certificate.

So is there a proper way to detect PEM content (mayb PEMReader and then instance of on the result. I tried with a ---- PRIVATE KEY ----- file but it returned null also)?

Of course, I can manually detect if file contain -----BEGIN CERTIFICATE----- or -----BEGIN PRIVATE KEY----- but I find this very careless.

Thank you !

jww
  • 97,681
  • 90
  • 411
  • 885
Kharlan
  • 31
  • 1
  • 3
  • Why can't you just try and load it and a handle the case where it returns null? Isn't that exactly what you are looking for? – Luke Joshua Park Nov 02 '16 at 19:07
  • `-----BEGIN CERTIFICATE-----` is called a pre-encapsulation boundary and `-----END CERTIFICATE-----` is called a post-encapsulation boundary. That is the way you check the PEM type according to [RFC 1421](http://tools.ietf.org/rfc/rfc1421.txt). There is nothing careless about it. Also see [Where is the PEM file format specified?](http://stackoverflow.com/q/5355046) on Stack Overflow and [PEM file format rfc draft request](https://www.ietf.org/mail-archive/web/pkix/current/msg03563.html) on the IETF mailing lists. – jww Nov 02 '16 at 20:23

0 Answers0