2011-01-29 139 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