【问题标题】:How to convert openssl RSA structure to char * and back?如何将 openssl RSA 结构转换为 char * 并返回?
【发布时间】:2019-03-29 17:23:16
【问题描述】:

这个问题很可能是重复的,如果是这样,我很抱歉,但无法谷歌解决方案。

给定:

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

我该怎么做?谢谢

【问题讨论】:

  • 当然有
  • 这个链接能满足你的需要吗? stackoverflow.com/questions/5927164/…
  • 您可以直接访问 rsa 结构。这有帮助吗? stackoverflow.com/questions/10512295/…
  • @MFisherKDX:不在 1.1.0 中,9 个月后将是唯一支持的上游版本。 Andrey:你想只在同一个进程中恢复,还是在不同的进程、系统或程序中恢复?后者要求您转换为序列化形式并返回; OpenSSL 支持的两种序列化形式(直接)是 der 和 pem,如 jww 在 #5927164 中详述,尽管您可以根据需要实现其他内容
  • 考虑i2d_RSAPrivateKeyd2i_RSAPrivateKey。它们可能不是最紧凑和最有效的序列化,但它们由稳定的 API 直接支持。

标签: c openssl rsa


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2013-10-12
    • 2015-09-19
    • 2021-09-05
    • 1970-01-01
    • 2015-07-21
    • 2012-01-11
    相关资源
    最近更新 更多