title: Programmatically verify certificate chain using OpenSSL API
body: <p>This is very similar to other questions but the ones I've looked at either don't have an answer or don't quite ask the same question.  I have a self-signed CA certificate, and two other certificates that are signed with that CA certificate.  I'm fairly sure the certificates are correct, because 'openssl verify' works:</p>
  <pre><code>$ openssl verify -CAfile ca.pem server.pem
  server.pem: OK
  </code></pre>
  <p>(The above is from memory, I don't have them in front of me, so it may be slightly off).</p>
  <p>Now I want to verify the certificates programatically. I have a utility function with pseudocode below:</p>
  <pre><code>int verify_cert(X509 *cert, X509 *cacert)
  {
       int ret;
       X509_STORE *store;
       X509_STORE_CTX *ctx;
  
       store = X509_STORE_new();
       X590_STORE_add_cert(store, cacert);
  
       ctx = X509_STORE_CTX_new();
       X509_STORE_CTX_init(ctx, store, cert, NULL);
  
       ret = X509_verify_cert(ctx);
  
       /* check for errors and clean up */
  }
  </code></pre>
  <p>My problem is that the above code always returns 'failed to find issuer certificate'.  What have I done wrong?  I believe I am creating a new store, adding the cacert, creating a new context, and adding the child cert to be verified to the context with a pointer to the store which contains the CA.  I'm pretty obviously doing something wrong, but I'm unsure what.</p>
  <p>Any ideas?</p>
  <p><strong>Update:</strong> I'm aware I can save these certs to disk and use something like X509_LOOKUP_file or something similar. I'm looking for a solution that doesn't touch the disk unnecessarily.</p>