#include <iostream>
#include <openssl/x509v3.h>
#include <openssl/pem.h>
using namespace Std;
#define USER_CERT "User Certificate Path"//Here is a PEM format certificate
#define CA_CERT "Root certificate Path"
int main ()
{
Ssleay_add_all_algorithms ();
X509_store_ctx *ctx = NULL; Certificate store handle
X509_store *pcacertstore = NULL; Certificate store
X509 *pcert = NULL; X509 certificate structure body, saving user certificate
X509 *pcacert = NULL; X509 The certificate structure body, saving the root certificate
X509_CRL *crl = NULL; X509_CRL structure body, saving CRL
Stack_of (X509) *certstack = NULL;
BIO * Pbio = NULL;
Pbio = Bio_new_file (User_cert, "R");
Pcert = pem_read_bio_x509 (pbio,null,null,null);
if (Pcert = NULL)
{
cout<< failed to read the user certificate. "<<endl;
return-1;
}
Bio_free (Pbio);
Pbio = NULL;
Pbio = Bio_new_file (Ca_cert, "R");
Pcacert = pem_read_bio_x509 (pbio,null,null,null);
Bio_free (Pbio);
Pbio = NULL;
if (Pcacert = NULL)
{
cout<< "Open Root certificate Failed" <<endl;
return-1;
}
Pcacertstore = X509_store_new (); New X509 certificate Store
X509_store_add_cert (Pcacertstore,pcacert); To add a root certificate to the certificate store
Sets the check CRL flag bit, and if this flag bit is set, the CRL is checked, otherwise the CRL is not checked.
Reading CRL Files
CRL = PEM_READ_BIO_X509_CRL (pbio,null,null,null);
if (crl==null)
{
X509_free (Pcacert);
cout<< "Read Revocation list file failed" <<endl;
return-1;
}
Bio_free (Pbio);
Pbio = NULL;
X509_store_set_flags (Pcacertstore,x509_v_flag_crl_check);
X509_STORE_ADD_CRL (PCACERTSTORE,CRL); To add a CRL to the certificate store
CTX = X509_store_ctx_new (); New certificate store handle
int ret = X509_store_ctx_init (ctx,pcacertstore,pcert,certstack); Initialize root certificate store, user certificate 1
if (Ret!= 1)
{
cout<< "X509_store_ctx_init Err" <<endl;
X509_free (Pcert);
X509_free (Pcacert);
X509_store_ctx_cleanup (CTX);
X509_store_ctx_free (CTX);
X509_store_free (Pcacertstore);
return-1;
}
Verifying user certificates
ret = X509_verify_cert (CTX);
if (Ret!= 1)
{
cout<< "Verify CER err.error=" <<ctx->error<< "info:" <<x509_verify_cert_error_string ( Ctx->error) <<endl;
}
Free memory
X509_free (Pcert);
X509_free (Pcacert);
X509_store_ctx_cleanup (CTX);
X509_store_ctx_free (CTX);
X509_store_free (Pcacertstore);
cout<< "ok!" <<endl;
return 0;
}