vishaln
vishaln

Reputation: 11

Convert certificate to byte array

How to convert a certificate(PEM/DER format) into byte array?

I don't have file system on my device and want to use the client certificate on it. So I want to copy this SSL certificate into a buffer(unsigned char). I have certificate file on my windows machine.

What is the right way to convert the certificate into array? Simple character copy will work?

Vishal N

Upvotes: 1

Views: 6726

Answers (2)

Akhil V Suku
Akhil V Suku

Reputation: 912

check this code, explanations are added as comments ,

1 Load the file into BIO structure

2 Convert it to x509 using PEM_read_bio_X509_AUX

3 convert the x509 to unsigned char * using 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;
} 

check the i2d_X509, PEM_read_bio_X509_AUX functions for more details.

This buffer can be used to create PCCERT_CONTEXT structure.

Upvotes: 2

Rudi
Rudi

Reputation: 19950

When you use gcc+gnu-binutils+openssl, you can use ld to include a file literal into the program. Then you use d2i_X509 to parse the literal into a X509 structure.

First run ld -r -b binary -o cert.crt.o cert.crt (cert.crt MUST be in DER form, I don't know if .crt is the correct extension for 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;
}

Then you compile this program with gcc -o ct example.c cert.crt.o -lcrypto.

Upvotes: 0

Related Questions