2011-01-29 230 views
1

如何將證書(PEM/DER格式)轉換爲字節數組?將證書轉換爲字節數組

我沒有在我的設備上的文件系統,並希望在其上使用客戶端證書。所以我想複製這個SSL證書到一個緩衝區(unsigned char)。我的Windows機器上有證書文件。

將證書轉換爲數組的正確方法是什麼?簡單的字符複製將起作用?

維沙爾ň

+0

你使用哪個庫和編譯器+鏈接器? – Rudi 2011-01-31 12:12:47

回答

0

當你使用gcc + GNU-的binutils + OpenSSL的,您可以使用ld包括文本到程序的文件。然後,您使用d2i_X509將文字解析爲X509結構。

首次運行ld -r -b binary -o cert.crt.o cert.crt(cert.crt必須是DER格式,我不知道.crt是否是DER的正確擴展名)。

example.c

#include <openssl/x509.h> 
#include <stdio.h> 

extern unsigned char _binary_cert_crt_start[]; 
extern unsigned char _binary_cert_crt_end[]; 

int main() 
{ 
    X509 *cert; 
    const unsigned char *buf = _binary_cert_crt_start; 
    unsigned const char** inp = &buf; 
    cert = d2i_X509(NULL, inp, _binary_cert_crt_end-_binary_cert_crt_start); 
    printf("%p\n", cert); 
    return !cert; 
} 

然後你gcc -o ct example.c cert.crt.o -lcrypto編譯這個程序。

1

檢查該代碼,解釋被添加註釋,

1將文件加載到BIO結構

2將其轉換爲使用PEM_read_bio_X509_AUX

3轉換X509爲unsigned char X509 *使用i2d_X509

int main() 
{  
    X509 *x509;  
    BIO *certBio = BIO_new(BIO_s_file()); 
    char * path = "E:\\share\\TempCert.pem"; /* directory path where certificate exists*/ 
    int len; 
    unsigned char *buf; 

    buf = NULL; 
    BIO_read_filename(certBio, path); 
    x509 = PEM_read_bio_X509_AUX(certBio, NULL, 0, NULL);  /*loading the certificate to x509 structure*/ 
    len = i2d_X509(x509, &buf);  /*loading the certificate to unsigned char buffer*/ 

    /* You can use this buf as BYTE array since BYTE is typedef of unsigned char and len will contain the length(size) of the certificate */ 
    BIO_free_all(certBio); 
    return 0; 
} 

檢查i2d_X509PEM_read_bio_X509_AUX函數的更多細節。

該緩衝區可用於創建PCCERT_CONTEXT結構。

+0

我有相反的問題:如何將字節數組轉換爲證書? – Kyrol 2017-08-16 18:18:09