如何验证您的私人CA发布的公钥?

Joh*_*ohn 15 c++ openssl

我创建了一个CA证书,并用它来发布公钥.在将来的某个日期,我需要验证加载的证书是否由我的CA颁发.

我如何使用OpenSSL API(c ++)做到这一点?

Joh*_*ohn 17

我已将verify.c(在openssl/apps /中)减少到所需的最小功能.假设:cert和CA证书都是PEM格式文件.无需CRLS或可信列表检查.

使用cert和CA PEM文件的路径调用verify().

static int verify(const char* certfile, const char* CAfile);
static X509 *load_cert(const char *file);
static int check(X509_STORE *ctx, const char *file);

int verify(const char* certfile, const char* CAfile)
{
    int ret=0;
    X509_STORE *cert_ctx=NULL;
    X509_LOOKUP *lookup=NULL;

    cert_ctx=X509_STORE_new();
    if (cert_ctx == NULL) goto end;

    OpenSSL_add_all_algorithms();

    lookup=X509_STORE_add_lookup(cert_ctx,X509_LOOKUP_file());
    if (lookup == NULL)
        goto end;

    if(!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM))
        goto end;

    lookup=X509_STORE_add_lookup(cert_ctx,X509_LOOKUP_hash_dir());
    if (lookup == NULL)
        goto end;

    X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);

    ret = check(cert_ctx, certfile);
end:
    if (cert_ctx != NULL) X509_STORE_free(cert_ctx);

    return ret;
}

static X509 *load_cert(const char *file)
{
    X509 *x=NULL;
    BIO *cert;

    if ((cert=BIO_new(BIO_s_file())) == NULL)
        goto end;

    if (BIO_read_filename(cert,file) <= 0)
        goto end;

    x=PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
end:
    if (cert != NULL) BIO_free(cert);
    return(x);
}

static int check(X509_STORE *ctx, const char *file)
{
    X509 *x=NULL;
    int i=0,ret=0;
    X509_STORE_CTX *csc;

    x = load_cert(file);
    if (x == NULL)
        goto end;

    csc = X509_STORE_CTX_new();
    if (csc == NULL)
        goto end;
    X509_STORE_set_flags(ctx, 0);
    if(!X509_STORE_CTX_init(csc,ctx,x,0))
        goto end;
    i=X509_verify_cert(csc);
    X509_STORE_CTX_free(csc);

    ret=0;
end:
    ret = (i > 0);
    if (x != NULL)
        X509_free(x);

    return(ret);
}
Run Code Online (Sandbox Code Playgroud)

  • 你能用评论来解释代码吗?我无法理解这个验证过程的逻辑 (4认同)
  • 你不需要调用`X509_STORE_add_lookup(... X509_LOOKUP_hash_dir());`和`X509_LOOKUP_add_dir(NULL,...);`因为你提供了你的CA文件. (2认同)
  • 您可以在“X509_STORE_set_flags(ctx, 0);”的上下文中添加标志。`X509_V_FLAG_X509_STRICT | X509_V_FLAG_CHECK_SS_SIGNATURE | X509_V_FLAG_POLICY_CHECK` 可能是不错的选择。一定要远离`X509_V_FLAG_ALLOW_PROXY_CERTS`。 (2认同)