Converting .crt to .pem using OpenSSL API

核能气质少年 提交于 2020-12-07 04:38:48

问题


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.


回答1:


.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");
}


来源:https://stackoverflow.com/questions/26142763/converting-crt-to-pem-using-openssl-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!