使用 OpenSSL 从内存中读取公钥/私钥 [英] Reading Public/Private Key from Memory with OpenSSL
问题描述
我在我的项目中使用公钥/私钥来加密/解密一些数据.
I am using Public/Private Keys in my project to encrypt/decrypt some data.
我在服务器上托管一个公钥(public.pem").
I am hosting a public key ("public.pem") on a server.
public.pem"看起来像这样:
"public.pem" looks like this:
-----BEGIN PUBLIC KEY-----
.....
.....
-----END PUBLIC KEY-----
我写了一个客户端来下载这个公钥并将它保存到磁盘,然后调用 OpenSSL 的 PEM_read_RSA_PUBKEY() 和一个文件描述符到那个文件.这个操作效果很好,结果是一个可以加密的 RSA 对象.
I wrote a client side that downloads this public key and save it to disk and then calls OpenSSL's PEM_read_RSA_PUBKEY() with a File descriptor to that file. This operation works great and the result is an RSA object that is ready for encryption.
我想避免每次都将公钥写入磁盘(因为我已经在内存中有缓冲区).
I would like to avoid writing the public key to disk each time (since i have the buffer in memory already).
如何在不将缓冲区保存到磁盘的情况下执行相同的操作?我注意到一个名为:PEM_read_bio_RSAPublicKey() 的函数,但我不确定它是否使用了 BIO 结构.我走在正确的道路上吗?
How can i do the same operation without saving the buffer to disk? I noticed a function called: PEM_read_bio_RSAPublicKey() but i am not sure of it's usage of BIO structure. Am I on the right path?
所以真正的问题是:如何直接从内存中而不是从文件描述符中读取 RSA 对象的公钥/私钥.
So the real question would be: How do I read a public/private key to an RSA object straight from memory and not from a file descriptor.
推荐答案
您走对了.您必须通过 BIO_new_mem_buf()
通过 BIO 缓冲区将 PEM 密钥包装在内存中.换句话说,类似于:
You are on the right track. You must wrap the PEM key already in memory by means of a BIO buffer via BIO_new_mem_buf()
. In other words, something like:
BIO *bufio;
RSA *rsa
bufio = BIO_new_mem_buf((void*)pem_key_buffer, pem_key_buffer_len);
PEM_read_bio_RSAPublicKey(bufio, &rsa, 0, NULL);
同样的方法对 RSA 私钥有效(通过 PEM_read_bio_RSAPrivateKey
),但在这种情况下,您肯定需要满足密码短语.查看手册页了解详情.
The same approach is valid for an RSA private key (via PEM_read_bio_RSAPrivateKey
), but in that case you most certainly need to cater for the pass phrase. Check the man page for details.
这篇关于使用 OpenSSL 从内存中读取公钥/私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!