【问题标题】:How to Read the certificates file from the PKCS7.p7b certificate file using openssl?如何使用 openssl 从 PKCS7.p7b 证书文件中读取证书文件?
【发布时间】:2011-06-16 08:32:39
【问题描述】:

我正在获取 PKCS7 文件 (p7b)。我想读取文件的内容并提取 X509 结构的证书。

如何使用 openssl 库从 PKCS 容器访问单个证书?

【问题讨论】:

    标签: c++ certificate openssl x509 pkcs#7


    【解决方案1】:

    我使用了以下程序:

    #include <stdio.h>
    #include <openssl/pkcs7.h>
    #include <openssl/x509.h>
    #include <openssl/bio.h>
    #include <openssl/pem.h>
    
    int main(int argc, char **argv)
    {
        PKCS7 *p7 = NULL;
        BIO *in = BIO_new(BIO_s_file());
        BIO *out = BIO_new(BIO_s_file());
        int der = 0; /* Input from DER or PEM ? */
        int text = 0; /* Dump text or output PEM ? */
        STACK_OF(X509) *certs = NULL;
        int i;
    
        CRYPTO_malloc_init();                                               \
        ERR_load_crypto_strings();
        OpenSSL_add_all_algorithms();
    
        BIO_set_fp(out, stdout, BIO_NOCLOSE);
        BIO_read_filename(in, argv[1]);
        p7 = der ?
            d2i_PKCS7_bio(in, NULL) :
            PEM_read_bio_PKCS7(in, NULL, NULL, NULL);
    
        i = OBJ_obj2nid(p7->type);
        if(i == NID_pkcs7_signed) {
            certs = p7->d.sign->cert;
        } else if(i == NID_pkcs7_signedAndEnveloped) {
            certs = p7->d.signed_and_enveloped->cert;
        }
    
        for (i = 0; certs && i < sk_X509_num(certs); i++) {
            X509 *x = sk_X509_value(certs,i);
            if(text) {
                X509_print(out, x);
            } else {
                PEM_write_bio_X509(out,x);
            }
        }
    }
    

    它基于 openssl-1.0.0d/apps/pkcs7.c 并且很容易编译(在 Linux 或 Mac OS X 上)(前提是您将其保存为 readp7.c):

    gcc -o readp7 readp7.c -lcrypto
    

    您可以使用 openssl 创建文件并像这样读取它们:

    openssl crl2pkcs7 -nocrl -certfile a.crt -certfile b.crt -out test.p7b
    ./readp7 test.p7b
    

    【讨论】:

    • 感谢代码。它运行良好..我的错误是我搜索 API 而不是访问结构 (PKCS7) 感谢提醒我的逻辑。
    • 嗨,我有 PKCS#7 blob,并使用您的技术迭代链中的证书。现在,我想通过在其 DER 表示上计算其 sha256 来验证每个证书,并将其与预先计算的值进行匹配。但是我在'x'里面找不到指纹,也许你知道我在哪里可以找到每个证书的指纹?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2011-11-13
    • 2021-02-22
    • 2010-10-08
    • 2011-04-18
    • 1970-01-01
    相关资源
    最近更新 更多