首页 > 解决方案 > 通过 C++ 从 PKCS7 (CMS) 获取详细信息

问题描述

我有target.cert文件,想获取证书 endDate 和 startDate 等详细信息

openssl pkcs7 -in target.cert -inform DER -print_certs -out cert_pem

openssl x509 -in cert.pem -enddate -startdate -noout

并且输出是开始和结束日期,并且想要做同样的事情,但来自 C++ 代码。

FILE* fp;
if (!(fp = fopen("target.cert", "rb"))) { 
fprintf(stderr, "Error reading input pkcs7 file\n" ); 
exit(1); 
} 
PKCS7 *p7; 
p7 = d2i_PKCS7_fp(fp, NULL);

p7没有像“startDate”这样的字段或解析字段的能力。

如何通过 C++ 获取“开始/结束日期”?

标签: c++copensslcryptography

解决方案


PKCS7 没有开始日期/结束日期。它里面的证书可以。您需要先提取它们并询问他们的日期。像这样的东西应该可以解决问题:

STACK_OF(X509) *certs = NULL;

// find out where the certs stack is located
int nid = OBJ_obj2nid(p7->type);
if(nid == NID_pkcs7_signed) {
    certs = p7->d.sign->cert;
} else if(nid == NID_pkcs7_signedAndEnveloped) {
    certs = p7->d.signed_and_enveloped->cert;
}

// go over all the certs in the chain (you can skip this and look only at the first 
// certificate if you don't care for the root CA's certificate expiration date)
for (int i = 0; certs && i < sk_X509_num(certs); i++)  {
    X509 *cert = sk_X509_value(certs, i);
    const ASN1_TIME *start = X509_get0_notBefore(cert);
    const ASN1_TIME *end = X509_get0_notAfter(cert);
    // do whatever you will with the dates
}

推荐阅读