2014/08/22

[OpenSSL]利用PEM_write_bio_RSAPrivateKey()來把DER格式轉換成PEM

上一篇([OpenSSL] 利用PEM_write_bio_X509()來把DER格式轉PEM格式)利用程式碼把Certificate轉乘PEM的格式,而這篇則是要把Private Key來轉換成PEM格式。

首先,把PEM的格式先轉換成DER。
openssl rsa -inform PEM -in private_key.pem -outform DER -out private_key.bin



然後透過程式碼轉換,參考底下
rsa_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;
    BIO *out=NULL;
    BIO *bio_err=NULL;
    const EVP_CIPHER *enc=NULL;
    BIO *key;
    EVP_PKEY *pkey=NULL;
    RSA *rsa=NULL;
    char *passout = NULL;
    int i;
    int ret = -1;

    char *keyFile, *pemFile;
    keyFile = argv[1];
    pemFile = argv[2];

    if (bio_err == NULL)
        bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
    if ((key=BIO_new(BIO_s_file())) == NULL)
    {
        ERR_print_errors(bio_err);         goto end;     }

    if (BIO_read_filename(key,keyFile) <= 0)
    {
        BIO_printf(bio_err, "Error opening %s %s\n", "Private Key", keyFile);         ERR_print_errors(bio_err);         goto end;     }

    pkey=d2i_PrivateKey_bio(key, NULL);
    if (pkey == NULL)
    {
        BIO_printf(bio_err,"unable to load %s\n", "Private Key");         ERR_print_errors(bio_err);     }
    if (pkey != NULL)
        rsa = EVP_PKEY_get1_RSA(pkey);     EVP_PKEY_free(pkey);

    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_RSAPrivateKey(out,rsa,enc,NULL,0,NULL,passout);
    if (i <= 0)
    {
        BIO_printf(bio_err,"unable to write key\n");         ERR_print_errors(bio_err);     } else
        ret = 0;
    printf("rsa DER convert to PEM successfully...\n");
end:
    BIO_free_all(out);
    BIO_free_all(key);
    RSA_free(rsa);
    OPENSSL_free(passout);
    return ret;
}

編譯
gcc rsa_DERtoPEM.c -o rsa_DERtoPEM -lssl -lcrypto


執行,把剛轉換出來DER格式的Private Key代入
./rsa_DERtoPEM private_key.bin private_key_out.pem

比較兩個檔案的結果
cat private_key_out.pem
cat private_key.pem


程式碼轉換的結果會與下列指令相同
openssl rsa -inform DER -in private_key.bin -outform PEM -out private_key_out.pem
有興趣可以試試看!

沒有留言:

張貼留言