4

我需要从 x509 证书中检索信息以验证密钥使用情况。例如,我需要确保证书可用于数字签名 (80)。

它可以通过以下代码段打印出来,但我实际上想验证证书是否具有特定属性。我需要的是一种方法boolean certHasAbility(X509 * cert, int purpose );,例如目的可以是DigitalSignature(80)Key Encipherment(20)

STACK_OF(X509_EXTENSION) *ext_list;

ext_list = cert->cert_info->extensions;
outbio  = BIO_new_fp(stdout, BIO_NOCLOSE);

if(sk_X509_EXTENSION_num(ext_list) <= 0)
    return 1;

for (int i=0; i<sk_X509_EXTENSION_num(ext_list); i++) {
    ASN1_OBJECT *obj;
    X509_EXTENSION *ext;

    ext = sk_X509_EXTENSION_value(ext_list, i);

    obj = X509_EXTENSION_get_object(ext);
    BIO_printf(outbio, "\n");
    BIO_printf(outbio, "Object %.2d: ", i);
    i2a_ASN1_OBJECT(outbio, obj);
    BIO_printf(outbio, "\n");
    X509V3_EXT_print(outbio, ext, NULL, NULL);
    BIO_printf(outbio, "\n");
}
4

1 回答 1

1

我会使用X509_get_ext_d2i功能:

static void print_my_key_usage(X509 *cert)
{
    ASN1_BIT_STRING *usage = X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL);
    if (usage && (usage->length > 0))
    {
        if (usage->data[0] & 0x80)
            printf("digitalSignature\n");
        ....
        if (usage->data[0] & 0x08)
            printf("keyAgreement\n");
        if (usage->data[0] & 0x04)
            printf("keyCertSign\n");
        if (usage->data[0] & 0x02)
            printf("cRLSign\n");
    }
}

您可以从RFC5280中找到位的详细信息。因为位串中可能有超过 1 个字节,所以您需要在函数中以某种方式处理它:

boolean certHasAbility(X509 *cert, int purpose)
{
    ASN1_BIT_STRING *usage = X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL);
    if (usage)
    {
        if (usage->length == 1)
        {
            return (usage->data[0] & purpose) == purpose;                
        }
        else
        {
            // TODO: handle different lengths.
        }
    }
}
于 2018-03-15T15:11:26.660 回答