X509_verify_cert函数负责用来验证证书的有效性,函数原型如下int X509_verify_cert(X509_STORE_CTX *ctx),验证成功返回1,失败返回其他值,失败的原因可以通过long nCode = X509_STORE_CTX_get_error(ctx);const char * pChError = X509_verify_cert_error_string(nCode);得到下面来演示一下如何使用这个函数int VerifyCertificate(){ //声明X509_STORE用来存储证书链 X509_STORE * certChain = NULL; //证书链上下文 X509_STORE_CTX *ctx = NULL; //初始化证书链 cerChain = X509_STORE_new(); //通过这个函数将被信任的证书加入信任链,rootCert是指被信任的证书, for(int i = 0 ; i < nTrustCount ; i++) { X509 * rootCert = GetTrustCert();//这个函数openssl中没有,用来读取可以被信任的证书 X509_STORE_add_cert(certChain,rootCert); } //为证书链上下文分配内存 ctx = X509_STORE_CTX_new(); //初始化证书链上下文,certChain是证书链,cert是要被验证的证书 X509_STORE_CTX_init(ctx,certChain,cert,NULL); //在证书验证之前,可以通过设置flags来确定验证的内容,flags的内容在x509_vfy.h中声明/* Certificate verify flags */之后就是 X509_STORE_CTX_set_flags(ctx,flags); //验证证书,根据返回值可以确认X509证书是否有效,也可以根据X509_STORE_CTX_get_error和X509_verify_cert_error_string函数来确认无效原因 int nX509Verify = X509_verify_cert(ctx); if (1 != nX509Verify ) { long nCode = X509_STORE_CTX_get_error(ctx); const char * pChError = X509_verify_cert_error_string(nCode); } //释放内存,这个很重要 if(NULL != ctx) { X509_STORE_CTX_free(ctx); } if (NULL != certChain) { X509_STORE_free(certChain); } return nX509Verify;}注:在验证证书的过程中,证书链的构造一定要完整,例如root为自签名的证书,颁发证书给TopCA,TopCA颁发证书给SecondCA,SecondCA颁发证书给User为了验证User的证书,root,TopCA,SecondCA都要在证书链中。接下来我们看看X509_verify主要验证的内容int X509_verify_cert(X509_STORE_CTX *ctx){ //检查颁发者 ctx->check_issued(ctx, x,x); //检查扩展部分 ok = check_chain_extensions(ctx); /* Check name constraints ,检查名称约束*/ ok = check_name_constraints(ctx); /* The chain extensions are OK: check trust,检查信任部分 */ ok = check_trust(ctx); /* Check revocation status,检查撤销状态*/ ok = ctx->check_revocation(ctx); /* At this point, we have a chain and need to verify it */ ok=internal_verify(ctx); /* If we get this far evaluate policies */ ok = ctx->check_policy(ctx);}在internal_verify有检查证书有效期的函数,即X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time);ASN1_TIME可以通过X509_get_notBefore()与X509_get_notAfter()两个函数来得到,time_t为从1970年1月1日凌晨算起的秒数,
转载于:https://www.cnblogs.com/Dennis-mi/articles/3267299.html