EVP_PKEY_keygen()会将密钥对生成为字符串吗?

时间:2017-03-13 19:17:39

标签: c encryption openssl

这是我现在的代码片段,它运行良好

/* Generate key */
if (EVP_PKEY_keygen(ctx, &pkey) <= 0)
    goto cleanup;


// write rsa private key to file
bio_private = BIO_new_file("private_new.pem", "w+");
ret = PEM_write_bio_PrivateKey(bio_private, pkey, NULL, NULL, 0, NULL, NULL);
if (ret != 1) {
    goto cleanup;
}
BIO_flush(bio_private);

// write rsa public key to file
bio_public = BIO_new_file("public_new.pem", "w+");

ret = PEM_write_bio_PUBKEY(bio_public, pkey);
if (ret != 1) {
    goto cleanup;
}
BIO_flush(bio_public);

而不是使用

PEM_write_bio_PrivateKey(bio_private, pkey, NULL, NULL, 0, NULL, NULL);

我希望将生成的密钥文本放入字符串而不是文件中。我不希望它写入磁盘,只是写入内存中的字符串。是否有PEM_功能来执行此操作?或任何其他方式?非常感谢您的帮助

2 个答案:

答案 0 :(得分:3)

使用

writers <- list(europe=europe, africa=africa,asia=asia)
writersafter20 <- lapply(writers, subset, Writer.At>=20)

而不是

bio_private = BIO_new(BIO_s_mem());

here

您可以使用long BIO_get_mem_data(BIO *b, char **pp)访问bio_private = BIO_new_file("private_new.pem", "w+"); 中的数据:

  

BIO_get_mem_data()将pp设置为指向内存BIO数据开头的指针,并返回可用数据的总量。它是作为宏实现的。

答案 1 :(得分:0)

感谢Artjom的上述答案。有效!以下是更改的相关代码:

/* Generate key */
if (EVP_PKEY_keygen(ctx, &pkey) <= 0)
    goto cleanup;

// write private key to memory
bio_private = BIO_new(BIO_s_mem());
ret = PEM_write_bio_PrivateKey(bio_private, pkey, NULL, NULL, 0, NULL, NULL);
if (ret != 1)
{
goto cleanup;
}
BIO_flush(bio_private);

BIO_get_mem_data(bio_private, &private_key_text);
cout << "PRIVE KEY :\n" << private_key_text << endl;
// write public key to memory
bio_public = BIO_new(BIO_s_mem());    
ret = PEM_write_bio_PUBKEY(bio_public, pkey);
if (ret != 1)
{
goto cleanup;
}
BIO_flush(bio_public);

BIO_get_mem_data(bio_public, &public_key_text);

cout << "PUBLIC KEY :\n" << public_key_text << endl;