Search code examples
opensslx509certificatex509

How to initialize X509 object in OpenSSL library using .cer file?


I'm trying to implement OCSP functions of OpenSSL as described here and it requires X509 object as a parameter. All I have is x.509 certificate file in .cer format. How to init the X509 object using .cer certificate in OpenSSL? (I'm using OpenSSL 1.0.0g in XCode if it matters).


Solution

  • There are two main cases. I'll cover both here.

    Note that I've assumed that you're using C++. Your choice of platform, if it is sane, should have bindings for these functions.


    In the first case, your certificate file is in so-called PEM form. If you open up a certificate in a text editor and see some Base64-encoded data with human-readable headers, that's a PEM file. In that case, the function you want has the signature

    X509 *PEM_read_X509(FILE *fp, X509 **x, pem_password_cb *cb, void *u);
    

    The first argument is a pointer to a FILE object returned by fopen(). You can leave the last three arguments as NULL. This function returns a pointer to the X509 object created, or NULL upon error.


    In the second case, your certificate file is in so-called DER form. If you open up a certificate in a text editor and see some garbage, that's probably a DER file. In that case, the function you want has the signature

    X509 *d2i_X509_fp(FILE *fp, X509 **x);
    

    You should be able to leave the second argument NULL. This function returns a pointer to the X509 object created, or NULL on error.


    The official OpenSSL documentation is notoriously incomplete. If you're looking for a good reference manual, I can recommend O'Reilly's "Network Security with OpenSSL" (ISBN 978-0-596-00270-1). It's written for OpenSSL 0.9.6 / 0.9.7 and doesn't have complete coverage for some topics (e.g. CRLs), but covers all the important points and provides example code. If anything, it will help you become less lost :)