2017-02-13 23 views
2

У меня есть сертификат в формате PEM, который я хочу преобразовать в формат DER с использованием функций OpenSLL в C++.Преобразование PEM в DER в C++

Как я могу это сделать?

Спасибо.

+0

OpenSSL x509 -outform дер -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). Он показывает вам некоторые трюки C++ с 'unique_ptr' для управления ресурсами. – 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