x509 certificate verification in C

前端 未结 3 1655
庸人自扰
庸人自扰 2020-11-30 05:38

I do have certificates in DER and PEM format, my goal is to retrieve the fields of Issuer and Subject and verify the certificate with the CA public key and simultaneously ve

3条回答
  •  一生所求
    2020-11-30 05:52

    I use following code for verifying a certificate

    init CertStore:

    X509_STORE* m_store = X509_STORE_new();
    X509_LOOKUP* m_lookup = X509_STORE_add_lookup(m_store,X509_LOOKUP_file());    
    X509_STORE_load_locations(m_store, "CAFile.pem", NULL);
    X509_STORE_set_default_paths(m_store);
    X509_LOOKUP_load_file(m_lookup,"CAFile.pem",X509_FILETYPE_PEM)
    // alternative lookup by hashdir
    // X509_LOOKUP* m_lookup=X509_STORE_add_lookup(m_store,X509_LOOKUP_hash_dir());
    

    VerifyCert:

    X509_STORE_CTX *storeCtx = X509_STORE_CTX_new();
    X509_STORE_CTX_init(storeCtx,m_store,cert,NULL);
    X509_STORE_CTX_set_flags(storeCtx, X509_V_FLAG_CB_ISSUER_CHECK);
    if (X509_verify_cert(storeCtx) == 1)
    {
      printf("success");
    }
    else
    {
      printf("Verificatione rror: %s",X509_verify_cert_error_string(storeCtx->error));
    }
    X509_STORE_CTX_free(storeCtx);
    

    you also need to cleanup m_store

    if(m_store != NULL)
    {
       X509_STORE_free(m_store);
       m_store = NULL;
    }
    

提交回复
热议问题