這篇的目的是,格式上的轉換,除了用OpenSSL的指令來轉換之外,也可以用C函式來轉換,底下是用PEM_write_bio_X509()來把Certificate從DER格式轉換成PEM格式。
首先先用底下指令
openssl x509 -inform PEM -in certificate.pem -outform DER -out crtificate.bin
把x509 Certificate從PEM格式轉換成DER的格式。
然後利用程式碼來轉換,參考底下
x509_DERtoPEM.c
#include <stdio.h>
#include <stdlib.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
int main(int argc, char **argv)
{
ENGINE *e = NULL;
X509 *x=NULL;
BIO *out=NULL;
BIO *bio_err=NULL;
BIO *cert;
int i;
int ret = -1;
char *certFile, *pemFile;
certFile = argv[1];
pemFile = argv[2];
if (bio_err == NULL)
bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
if ((cert=BIO_new(BIO_s_file())) == NULL)
{
ERR_print_errors(bio_err);
goto end;
}
if (BIO_read_filename(cert,certFile) <= 0)
{
BIO_printf(bio_err, "Error opening %s %s\n", "Certificate", certFile);
ERR_print_errors(bio_err);
goto end;
}
x=d2i_X509_bio(cert,NULL);
if (x == NULL)
{
BIO_printf(bio_err,"unable to load certificate\n");
ERR_print_errors(bio_err);
goto end;
}
out=BIO_new(BIO_s_file());
if (out == NULL)
{
ERR_print_errors(bio_err);
goto end;
}
if (BIO_write_filename(out,pemFile) <= 0)
{
perror(pemFile);
goto end;
}
i=PEM_write_bio_X509(out,x);
if (!i)
{
BIO_printf(bio_err,"unable to write certificate\n");
ERR_print_errors(bio_err);
goto end;
} else
ret = 0;
printf("x509 DER convert to PEM successfully...\n");
end:
BIO_free_all(out);
BIO_free_all(cert);
X509_free(x);
return ret;
}
編譯
gcc x509_DERtoPEM.c -o x509_DERtoPEM -lssl -lcrypto
執行,把剛剛轉換出來DER格式的Certificate帶入
./x509_DERtoPEM certificate.bin certificate_out.pem
比較原本檔案,和用PEM_write_bio_X509()轉換出來的檔案
cat certificate.pem
cat certificate_out.pem
上面轉換出來的結果,會跟底下指令有相同的結果
openssl x509 -inform DER -in certificate.bin -outform PEM -out certificate_out.pem
有興趣可以自己玩玩看!
沒有留言:
張貼留言