Search code examples
ccertificateopensslx509readfile

openssl: how to read a .crt file..?


I want to read the certifi.crt file using OpenSSL API (not in commands). I have no idea how to do that. If any one knows, please help me. Thank you.

If you give example code that will be very helpful.


Solution

  • If the ".crt" extension refers to a PEM text file (begins with -----BEGIN CERTIFICATE----- followed by base64), then get started in the OpenSSL docs here.

    Here is some code to get you started (link with ssl, e.g. g++ a.c -lssl):

    #include <stdio.h>
    #include <openssl/x509.h>
    #include <openssl/pem.h>
    
    int main(int argc, char** argv)
    {
        FILE* f = fopen("certifi.crt", "r");
        if (f != NULL)
        {
            X509* x509 = PEM_read_X509(f, NULL, NULL, NULL);
            if (x509 != NULL)
            {
                char* p = X509_NAME_oneline(X509_get_issuer_name(x509), 0, 0);
                if (p)
                {
                    printf("NAME: %s\n", p);
                    OPENSSL_free(p);
                }
                X509_free(x509);
            }
        }
        return 0;
    }