我有一个x509证书加载到mbedtls中,我可以通过以下方式获取整个主题字段:
mbedtls_x509_dn_gets(p, n, cert.subject);
可以对输出进行字符串标记以提取特定字段,但这似乎容易出错。
是否有一种简单的方法来获取此字段的各个OID值,例如CN或OU条目?
答案 0 :(得分:0)
mbedtls_x509_dn_gets
是否不能使用type mbedtls_asn1_named_data
的解析的 ASN.1结构?您应该可以迭代遍历,直到找到您感兴趣的OID。您可以使用function mbedtls_asn1_find_named_data
来自动执行此操作。
答案 1 :(得分:0)
用法:
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;
}