2012-10-22 109 views
2

我在執行下面的代碼(請參見注釋)::X509_verify_cert返回0(零)

#include <stdio.h> 
#include <openssl/crypto.h> 
#include <openssl/err.h> 
#include <openssl/pem.h> 
#include <openssl/rand.h> 

#pragma comment(lib, "ssleay32.lib") 
#pragma comment(lib, "libeay32.lib") 

void verifyCertificate() ; 
X509 *loadCert(char*) ; 
void loadToStore(char*, X509_STORE*&) ; 

void verifyCertificate() 
{ 
    int i = 0 ; 
    char argv[50] = "C:\\My\\CA.pem" ; /* Details:: Issuer = Verisign Inc & Subject = Verisign Inc 
    char argv1[50] = "C:\\My\\mid1.pem" ; /* Details:: Issuer = Thawte & Subject = Verisign Inc 
    char argv2[50] = "C:\\My\\mid2.pem" ; /* Details:: Issuer = Verisign Inc & Subject = Verisign Inc 
    char argv3[50] = "C:\\My\\Signer.pem" ; /* Details:: Issuer = Verisign Inc & Subject = SignerOrganisation 

    X509 *cert = loadCert(argv3); 
    X509_STORE *store = X509_STORE_new(); 

    loadToStore(argv, store); 
    loadToStore(argv1, store); 
    loadToStore(argv2, store); 

    X509_STORE_CTX *ctx = X509_STORE_CTX_new(); 

    X509_STORE_CTX_init(ctx, store, cert, NULL); 

    i = X509_verify_cert(ctx); 
    printf("i = %d\n", i) ; // Returns i = 0 
    if (i != 1) 
     printf("%s", X509_verify_cert_error_string(ctx->error)); 
      // Returns "Certificate Signature Failure" 

    X509_STORE_CTX_cleanup(ctx); 
    X509_STORE_CTX_free(ctx); 
    X509_STORE_free(store); 
    ctx = NULL; 
    store = NULL; 
} 

void loadToStore(char* file, X509_STORE *&store) 
{ 
    X509 *cert = loadCert(file); 
    if (cert != NULL) 
     X509_STORE_add_cert(store, cert); 
    else 
     printf("Can not load certificate"); 
} 

X509 *loadCert(char* file) 
{ 
    FILE *fp = fopen(file, "rb"); 
    X509 *cert = PEM_read_X509(fp, NULL, NULL, NULL); 
    fclose(fp); 
    return cert; 
} 

int main(int argc, char** argv) 
{ 
    verifyCertificate() ; 
    return 0 ; 
} 

我已經提取的每一個證書包含的,然後在店裏加載它們。

問題:: X509_verify_cert正在返回零(0)。任何建議?

+0

什麼是X509_STORE_CTX_get_error在失敗時返回?請參閱https://www.openssl.org/docs/crypto/X509_verify_cert.html。 – jww

+0

什麼是'X509_STORE_add_cert'返回? 1表示成功,0表示失敗(來自1150行附近'x509.c'的源代碼)。 – jww

回答

1

X509_verify_cert僅爲有效證書鏈返回成功,即每個下一個證書必須由前一個證書籤名(除必須自簽名的1st以外)。要確定您是否擁有有效鏈,應提供有關您的Pem的完整信息。但考慮到您的意見,我發現CA.pem不簽署mid1.pem,因爲CA.pem的主題(Verisign Inc)不等於mid1.pem的發行人(Thawte)