2

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

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

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

4

3 回答 3

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);

...

就我而言,对于 teste 证书,它打印了“数字签名、不可否认性、密钥加密”

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

问候。

于 2012-04-13T15:24:18.943 回答
3

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

方法二:

     X509_check_ca(lcert) ;       
     //need to call before the 
     unsigned long lKeyusage= lCert->ex_kusage;
于 2012-04-16T11:00:45.350 回答
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填充标志的调用,由锁保护。

于 2015-08-10T00:59:33.850 回答