如何将openssl RSA结构转换为char *并返回?

安德烈·切尔努卡(Andrey Chernukha)

这个问题很可能是重复的,如果是这样,我对此表示歉意,但无法在Google上找到解决方案。

鉴于:

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

我想要类似的东西:

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

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

我怎么做?谢谢

安德烈·切尔努卡(Andrey Chernukha)

感谢Michael Dorgan向我指出了正确的方向。我最终拥有以下两个功能:

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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章