2012-04-04 447 views
2

我要检索从X509结构证书的密钥的使用价值,我想下面的代码如何从X509证书获取Keyusage值?

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

当我打印的lKeyusage值..有时我得到128 ...有时我为得到0相同的证书.. 任何人都可以告诉我什么是错误。? 如果我做错了,请给我一些示例代码或正确的API ..

+0

我在此主题中回复了一个可能的解决方案:http://stackoverflow.com/questions/9991147/how-to-read-the-keyusage-of-a-x509-v3-certificate/24714773#24714773 – 2014-07-12 16:10:36

回答

7

我认为最简单的方法是使用一个内存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 *。我可以告诉你,如果上述不符合你的需求。

问候。

+1

此代码将只能以可读格式打印密钥用法。 – Balamurugan 2012-04-16 11:09:12

2

我使用下面的代码来获取密钥使用情况值。 方法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 
    }     

方法2:

 X509_check_ca(lcert) ;  
    //need to call before the 
    unsigned long lKeyusage= lCert->ex_kusage; 
+0

在方法2中,你必须检查'ex_flags'的值,如果它有'EXFLAG_SET',这意味着设置了'ex_kusage'和'ex_xkusage',并且你不需要调用'X509_check_ca',你可以检查'v3_purp.c '更多细节 – bikram990 2017-09-11 05:55:30

0

ssl\ssl_lib.c,线2365,OpenSSL的v 1.0.2d:

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

X509_check_purpose(x, -1, 0); 

所以OpenSSL的开发人员使用此方法。

如果深入挖掘,您可能会发现调用x509v3_cache_extensions,即填充由锁保护的标志。