2017-02-13 94 views
2

我有一个PEM格式的证书,我想使用C++中的OpenSLL函数将其转换为DER格式。在C++中将PEM转换为DER

我该怎么办?

谢谢。

+0

OpenSSL的X​​509 -outform DER -in certificate.pem退房手续certificate.der https://www.sslshopper.com /ssl-converter.html – user1438832

+0

如何在C++中使用openssl函数执行此操作? – itayb

+0

另请参阅[使用OpenSSL RSA密钥与.Net](http://stackoverflow.com/q/30475758/608639)。它向您展示了一些使用'unique_ptr'管理资源的C++技巧。 – jww

回答

1

你可以不喜欢它 -

#include <stdio.h> 
#include <openssl/x509.h> 
#include <openssl/pem.h> 
#include <openssl/err.h> 

void convert(char* cert_filestr,char* certificateFile) 
{ 
    X509* x509 = NULL; 
    FILE* fd = NULL,*fl = NULL; 

    fl = fopen(cert_filestr,"rb"); 
    if(fl) 
    { 
     fd = fopen(certificateFile,"w+"); 
     if(fd) 
     { 
      x509 = PEM_read_X509(fl,&x509,NULL,NULL); 
      if(x509) 
      { 
       i2d_X509_fp(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"); 
    } 
} 


int main() 
{ 
    convert("abc.pem","axc.der"); 
    return 0; 
} 
+0

谢谢,只是一个问题,如果我把它作为字符串而不是文件,我该怎么做? 非常感谢你 – itayb

-1

试试这个 -

void convert(const unsigned char * pem_string_cert,char* certificateFile) 
{ 
    X509* x509 = NULL; 
    FILE* fd = NULL; 

    BIO *bio; 

    bio = BIO_new(BIO_s_mem()); 
    BIO_puts(bio, pem_string_cert); 
    x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL); 

    fd = fopen(certificateFile,"w+"); 
    if(fd) 
    { 
      i2d_X509_fp(fd, x509); 
    } 
    else 
    { 
     printf("can't open fd"); 
    } 
    fclose(fd); 
} 
+0

非常感谢 – itayb