2

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.

6
  • A major problem is that using sizeof on a pointer gives you the size of the pointer and not what it points to. Commented Oct 1, 2014 at 13:43
  • Also, in C you don't have to cast a pointer to void*, all pointers can implicitly be casted to (and from) void*. Commented Oct 1, 2014 at 13:45
  • oh no, so is 'char **size = malloc(sizeof(fl));' a posibility to get the right size? Commented Oct 1, 2014 at 13:58
  • The size if len, it's the size you need to pass to BIO_new_mem_buf. Commented Oct 1, 2014 at 14:01
  • ok thank you! fixed that! but the issue still exists.. Commented Oct 1, 2014 at 14:05

1 Answer 1

4

.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");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.