[openssl-users] verify certificate chain (in memory)

Lei Sun ls00722 at yahoo.com
Sat Mar 5 01:35:00 UTC 2016

  In my project I need to verify certificate chain sent from server. The chain has root->inter mediate -> server, 3 level chain. The server certificate files can be verified by "openssl verify" command:

openssl verify -CAfile root.crt server.crt

But I had to combine the root cert and intermediate cert into single file, to verify the whole chain via command line.

I wrote a test program to verify it with C program:
Note that I have converted the PEM cert file into DER binary, to minic exactly what server sent me.

The core part of the code in bellow:

int main(void)
    FILE *fp = NULL;
    size_t r_size, i_size, s_size;
    unsigned char *r, *i, *s;
    X509 *root, *inter, *server;
    X509_STORE *store;

    X509_STORE_CTX *store_ctx;
       int ret;

        if ((r = malloc(1024)) == NULL ||
        (i = malloc(1204)) == NULL ||
               (s = malloc(1024)) == NULL)
            return -1;

        /* read certs into buffer */
        r_size = read_cert("root.bin", r, 1024);
        i_size = read_cert("inter.bin", i, 1024);
     s_size = read_cert("server.bin", s, 1024);

root = d2i_X509(NULL, &r, r_size);
if (root == NULL)
            fprintf(stderr, "failed to convert root cert\n");
inter = d2i_X509(NULL, &i, i_size);
if (inter == NULL)
            fprintf(stderr, "failed to convert inter cert\n");
server = d2i_X509(NULL, &s, s_size);
if (server == NULL)
            fprintf(stderr, "failed to convert server cert\n");

store = X509_STORE_new();
X509_STORE_add_cert(store, root);
store_ctx = X509_STORE_CTX_new();

X509_STORE_CTX_init(store_ctx, store, inter, NULL);

ret = X509_verify_cert(store_ctx);

fprintf(stdout, "ret=%d\n", ret);
if (ret <= 0) {
ret = X509_STORE_CTX_get_error(store_ctx);
fprintf(stderr, "%d: %s\n", ret, X509_verify_cert_error_string(ret));

The above code gives me "certificate signature failure" error, I was only trying to verify intermediate cert with root cert.  Since I don't know how to verify the whole chain in memory.

Can anybody shed some lights on me? I googled around for a day with no luck. 


More information about the openssl-users mailing list