如何使用 mbedtls 从证书中提取单个 OID?

How can you extract individual OIDs from a certificate with mbedtls?

我将 x509 证书加载到 mbedtls 中,我可以通过以下方式获取整个主题字段:

mbedtls_x509_dn_gets(p, n, cert.subject);

可以对输出进行字符串标记化以提取特定字段,但这似乎容易出错。

是否有简单的方法来获取此字段的各个 OID 值,例如 CN 或 OU 条目?

mbedtls_x509_dn_gets 无法在 type mbedtls_asn1_named_data? You should be able to iterate through that until you find the OID you are interested in. You can use the function mbedtls_asn1_find_named_data 解析的 ASN.1 结构上工作以实现自动化。

用法:

const mbedtls_x509_name *name = &cert_ctx.subject;
char value[64];
size_t value_len;

value_len = find_oid_value_in_name(name, "CN", value, sizeof(value));
if(value_len)
{
    printf("CN: %s\n", value);
} else
{
    printf("Unable to find OID\n");
}

函数:

size_t find_oid_value_in_name(const mbedtls_x509_name *name, const char* target_short_name, char *value, size_t value_length)
{
    const char* short_name = NULL;
    bool found = false;
    size_t retval = 0;

    while((name != NULL) && !found)
    {
        // if there is no data for this name go to the next one
        if(!name->oid.p)
        {
            name = name->next;
            continue;
        }

        int ret = mbedtls_oid_get_attr_short_name(&name->oid, &short_name);
        if((ret == 0) && (strcmp(short_name, target_short_name) == 0))
        {
            found = true;
        }

        if(found)
        {
            size_t bytes_to_write = (name->val.len >= value_length) ? value_length - 1 : name->val.len;

            for(size_t i = 0; i < bytes_to_write; i++)
            {
                char c = name->val.p[i];
                if( c < 32 || c == 127 || ( c > 128 && c < 160 ) )
                {
                    value[i] = '?';
                } else
                {
                    value[i] = c;
                }
            }

            // null terminate
            value[bytes_to_write] = 0;

            retval = name->val.len;
        }

        name = name->next;
    }

    return retval;
}