我需要从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");
}
答案 0 :(得分: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.
}
}
}