how to get the Keyusage value from the X509 certif

2020-02-14 19:47发布

I want to retrieve the Key usage value from the X509 structured certificate , i tried the following code

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

When i print the lKeyusage value .. some times i get 128 ... sometimes i get 0 for the same certificate .. Can any one tell me what is the error .? If i am doing wrong please give me some sample code or Correct API ..

3条回答
叼着烟拽天下
2楼-- · 2020-02-14 20:16

From ssl\ssl_lib.c, line 2365, OpenSSL v 1.0.2d:

/* This call populates extension flags (ex_flags) */

X509_check_purpose(x, -1, 0);

So OpenSSL developers use this way.

If digging deeper, you may find call of x509v3_cache_extensions, that populate flags, guarded by locks.

查看更多
趁早两清
3楼-- · 2020-02-14 20:21

I used the below code to get the Key usage value . Method 1;

   //iCertificate is in X509 format
   ASN1_BIT_STRING* lASN1UsageStr;
   lASN1UsageStr=(ASN1_BIT_STRING *)X509_get_ext_d2i(iCertificate,NID_key_usage,NULL,NULL);
    if(lASN1UsageStr == NULL)
    {
        cout<<" get ext_d2i function returns errors";
    }
    else if(lASN1UsageStr->length > 0) 
    {
        lKeyUsage = lASN1UsageStr->data[0];
        if(lASN1UsageStr->length > 1)
        { 
               lKeyUsage |= lASN1UsageStr->data[1] << 8;
        }// else{}     
    } else 
    {
        lKeyUsage = -1;    //invalid keyusage
    }                

method 2:

     X509_check_ca(lcert) ;       
     //need to call before the 
     unsigned long lKeyusage= lCert->ex_kusage;
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-02-14 20:30

I think the easiest way is to use a memory 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);

...

In my case, for a teste certificate, it has printed "Digital Signature, Non Repudiation, Key Encipherment"

There are other ways, like using an ASN1_BIT_STRING *. I can show you if the above doesn't fit your needs.

Regards.

查看更多
登录 后发表回答