2012-04-04 156 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,即填充由鎖保護的標誌。