如何从X509证书中获取Keyusage值?

Bal*_*gan 2 openssl certificate ssl-certificate x509certificate x509

我想从X509结构化证书中检索密钥使用值,我尝试了以下代码

 X509* lcert=NULL;
 lCert=PEM_read(filename); // function will return the certificate in X509
unsigned long lKeyusage= lCert->ex_kusage;
Run Code Online (Sandbox Code Playgroud)

当我打印lKeyusage值...有时我得到128 ...有时我得到0相同的证书..谁能告诉我什么是错误.?如果我做错了请给我一些示例代码或正确的API ..

Fel*_*ipe 8

我认为最简单的方法是使用内存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);

...
Run Code Online (Sandbox Code Playgroud)

就我而言,对于teste证书,它已经打印出"数字签名,不可否认,关键加密"

还有其他方法,例如使用ASN1_BIT_STRING*.如果上述内容不符合您的需求,我可以告诉您.

问候.