简体   繁体   English

openssl在C中创建rsa密钥对并将其导出

[英]openssl create rsa key pair in C and export it

I want to create a RSA key pair in C/C++ and export it to a string to work with it. 我想在C / C ++中创建一个RSA密钥对,并将其导出到字符串以使用它。

I managed to create the key 我设法创建了钥匙

rsa = RSA_generate_key(bits, exp, NULL, NULL);
if(RSA_check_key(rsa)!=1){
    std::cout << "Error while checking key" << std::endl << std::flush;
}

pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);

From this point I can write the private and public key to a file with PEM_write_PUBKEY() and PEM_write_PrivateKey(). 从这一点开始,我可以使用PEM_write_PUBKEY()和PEM_write_PrivateKey()将私钥和公钥写入文件。 But what I want to do is to get the private and public key from pkey directly into a variable, preferable in the PEM format. 但是我要做的是将私钥和公钥从pkey直接转换为变量,最好是PEM格式。 I already looked around but couldn't find the right function. 我已经环顾四周,但是找不到正确的功能。 Any hints? 有什么提示吗?

If you really need the PEM representation, then PEM_write_bio_RSA_PUBKEY() and PEM_write_bio_RSAPrivateKey() (along with their read counterparts) are the functions you want; 如果您确实需要PEM表示形式,则需要使用PEM_write_bio_RSA_PUBKEY()PEM_write_bio_RSAPrivateKey() (以及它们的已read副本); give them memory BIOs to have them write into a memory buffer. 给他们内存BIO,使其写入内存缓冲区。

You can create a memory BIO by invoking eg 您可以通过调用例如创建内存BIO

BIO * b = BIO_new(BIO_s_mem());

and get the memory buffer by invoking 并通过调用获取内存缓冲区

void * buf;
BIO_get_mem_ptr(b, &buf);

You can also create a memory BIO around existing memory by invoking eg 您还可以通过调用例如在现有内存周围创建内存BIO

BIO * b = BIO_new_mem_buf(buf, 9001)

but the resulting BIO will be read-only. 但是生成的BIO将为只读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM