Search code examples
capiopensslpemcrt

Converting .crt to .pem using OpenSSL API


Can anyone show me how to convert .crt files to .pem files using the openssl API? I tried it like this:

FILE *fl = fopen(cert_filestr, "r");
fseek(fl, 0, SEEK_END);
long len = ftell(fl);
char *ret = malloc(len);
fseek(fl, 0, SEEK_SET);
fread(ret, 1, len, fl);
fclose(fl);
BIO* input = BIO_new_mem_buf((void*)ret, sizeof(ret));
x509 = d2i_X509_bio(input, NULL);
FILE* fd = fopen(certificateFile, "w+");
BIO* output = BIO_new_fp(fd, BIO_NOCLOSE);
X509_print_ex(output, x509, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
fclose(fd);

But that doesn't work, x509 is always NULL.


Solution

  • .crt certificate "may be encoded as binary DER or as ASCII PEM." (see http://info.ssl.com/article.aspx?id=12149).

    If your .crt file is already PEM encoded you don't need to convert it, just change the file name from .crt to .pem.

    If it is encoded as DER, convert it to PEM like in this example:

    X509* x509 = NULL;
    FILE* fd = NULL,*fl = NULL;
    
    fl = fopen(cert_filestr,"rb");
    if(fl) 
    {
        fd = fopen(certificateFile,"w+");
        if(fd) 
        {
            x509 = d2i_X509_fp(fl,NULL);
            if(x509) 
            {
                PEM_write_X509(fd,x509);
            }
            else 
            {
               printf("failed to parse to X509 from fl");
            }
            fclose(fd);
        }
        else
        {
            printf("can't open fd");
        }
       fclose(fl);
    }
    else 
    {
        printf("can't open f");
    }