x509证书验证

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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值