我认为最简单的方法是使用一个内存BIO:
...
X509 *lcert = NULL;
BUF_MEM *bptr = NULL;
char *buf = NULL;
int loc;
FILE *f = fopen("your cert goes here", "rb");
if((lcert = PEM_read_X509(f, &lcert, NULL, NULL)) == NULL){
// error handling...
}
loc = X509_get_ext_by_NID(lcert, NID_key_usage, -1);
X509_EXTENSION *ex = X509_get_ext(lcert, loc);
BIO *bio = BIO_new(BIO_s_mem());
if(!X509V3_EXT_print(bio, ex, 0, 0)){
// error handling...
}
BIO_flush(bio);
BIO_get_mem_ptr(bio, &bptr);
// now bptr contains the strings of the key_usage, take
// care that bptr->data is NOT NULL terminated, so
// to print it well, let's do something..
buf = (char *)malloc((bptr->length + 1)*sizeof(char));
memcpy(buf, bptr->data, bptr->length);
buf[bptr->length] = '\0';
// Now you can printf it or parse it, the way you want...
printf ("%s\n", buf);
...
在我的情况下,对于阿泰斯特证书,它已打印“数字签名,不可否认,密钥加密”
还有其他方法,如使用ASN1_BIT_STRING *。我可以告诉你,如果上述不符合你的需求。
问候。
我在此主题中回复了一个可能的解决方案:http://stackoverflow.com/questions/9991147/how-to-read-the-keyusage-of-a-x509-v3-certificate/24714773#24714773 – 2014-07-12 16:10:36