我認爲最簡單的方法是使用一個內存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