How to verify a X509 certificate in C

mmm picture mmm · Apr 5, 2013 · Viewed 15.4k times · Source

I have a certificate in X509 format. this a input parameters in a function. What I would like to do is to verify the validity of the certificate. How can it be done?

X509_verify_cert();

I found this function, but this does not accept a X509* certificate, it accepts X509_store and I only have a X509.

Thanks best regards.

Answer

mmm picture mmm · Apr 7, 2013

I am here just to post my answer as I found it with the above comments.

I had no certificate chain, so in the work I'm doing I only have a certificate generated by me programatically. I wanted to check the validity of it, so I created the following function, which checks the certificate against itself in other to verify the validity of it.

void check_certificate_validaty(X509* certificate)
{
    int status;
    X509_STORE_CTX *ctx;
    ctx = X509_STORE_CTX_new();
    X509_STORE *store = X509_STORE_new();

    X509_STORE_add_cert(store, certificate);

    X509_STORE_CTX_init(ctx, store, certificate, NULL);

    status = X509_verify_cert(ctx);
    if(status == 1)
    {
        printf("Certificate verified ok\n");
    }else
    {
        printf("%s\n", X509_verify_cert_error_string(ctx->error));
    }
}

Hope this helps someone :)