如何以编程方式从证书中提取信息?

时间:2013-04-03 12:49:55

标签: c openssl certificate x509 pkix

我已生成证书,但我希望能够从证书中提取信息,例如国家/地区,有效性,公钥等。我必须将从证书中重新获得的信息与我在C程序中存储的其他信息进行比较。

我知道如果我使用这样的函数,它会打印出证书信息:

void print_certificate(const char* cert)
{
    X509 *x509 = NULL;
    BIO *i = BIO_new(BIO_s_file());
    BIO *o = BIO_new_fp(stdout,BIO_NOCLOSE);

    if((BIO_read_filename(i, cert) <= 0) ||
       ((x509 = PEM_read_bio_X509_AUX(i, NULL, NULL, NULL)) == NULL)) {
           printf("Bad certificate, unable to read\n");
    }

    X509_print_ex(o, x509, XN_FLAG_COMPAT, X509_FLAG_COMPAT);   

    if(x509)
        X509_free(x509);
}

但我想要的只是信息的某些部分。怎么办呢?

由于

2 个答案:

答案 0 :(得分:4)

尝试grep _get_ /usr/include/openssl/x509.h

这里有一些你可能会觉得有用的东西:

EVP_PKEY *  X509_get_pubkey(X509 *x);
#define     X509_CRL_get_issuer(x) ((x)->crl->issuer)
#define     X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
#define     X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)

另请查看包含X509_print_ex的{​​{3}}的源代码。这可能是最有用的。

答案 1 :(得分:2)

参见OpenSSL的x509.h(例如here)。你会发现很多有用的功能。 例如:

#define     X509_get_version(x) ASN1_INTEGER_get((x)->cert_info->version)
/* #define  X509_get_serialNumber(x) ((x)->cert_info->serialNumber) */
#define     X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
#define     X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
#define     X509_extract_key(x) X509_get_pubkey(x) /*****/
#define     X509_REQ_get_version(x) ASN1_INTEGER_get((x)->req_info->version)
#define     X509_REQ_get_subject_name(x) ((x)->req_info->subject)
#define     X509_REQ_extract_key(a) X509_REQ_get_pubkey(a)
#define     X509_name_cmp(a,b)  X509_NAME_cmp((a),(b))
#define     X509_get_signature_type(x) EVP_PKEY_type(OBJ_obj2nid((x)->sig_alg->algorithm))

#define     X509_CRL_get_version(x) ASN1_INTEGER_get((x)->crl->version)
#define     X509_CRL_get_lastUpdate(x) ((x)->crl->lastUpdate)
#define     X509_CRL_get_nextUpdate(x) ((x)->crl->nextUpdate)
#define     X509_CRL_get_issuer(x) ((x)->crl->issuer)
#define     X509_CRL_get_REVOKED(x) ((x)->crl->revoked)

/* This one is only used so that a binary form can output, as in
 * i2d_X509_NAME(X509_get_X509_PUBKEY(x),&buf) */
#define     X509_get_X509_PUBKEY(x) ((x)->cert_info->key)