首页 > 解决方案 > How to convert openssl RSA structure to char * and back?

问题描述

This question is likely to be a duplicate, I apologize if so, but cannot google a solution.

Given:

RSA* rsa = RSA_generate_key(2048, RSA_3, NULL, NULL);

I would like to have something like:

const char* pubKey = pubKeyFromRSA(rsa);
const char* privKey = privKeyFromRSA(rsa);

//and then convert it back
RSA* newRSA = RSAFromPrivKey(privKey);

How do I do that? Thanks

标签: copensslrsa

解决方案


Thanks to Michael Dorgan who pointed me in the right direction. I ended up having these two functions:

const char* keyFromRSA(RSA* rsa, bool isPrivate)
{
    BIO *bio = BIO_new(BIO_s_mem());

    if (isPrivate)
    {
        PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, NULL);
    }
    else
    {
        PEM_write_bio_RSA_PUBKEY(bio, rsa);
    }

    const int keylen = BIO_pending(bio);
    char* key = (char *)calloc(keylen+1, 1);
    BIO_read(bio, key, keylen);
    BIO_free_all(bio);

    return key;
}

RSA* rsaFromPrivateKey(const char* aKey)
{
     RSA* rsa = NULL;
     BIO *bio = BIO_new_mem_buf(aKey, strlen(aKey));
     PEM_read_bio_RSAPrivateKey(bio, &rsa, 0, 0);
     BIO_free_all(bio);

     return rsa;
}

推荐阅读