如何使用 OpenSSL C 库将 RSA 密钥从二进制数据加载到 RSA 结构?

2022-01-07 00:00:00 c openssl rsa c++

目前我将我的私钥保存在一个文件 private.key 中,我使用以下函数加载它:

Currently I have my private key saved in a file, private.key, and I use the following function to load it:

RSA *r = PEM_read_RSAPrivateKey("private.key", NULL, NULL, NULL);

RSA *r = PEM_read_RSAPrivateKey("private.key", NULL, NULL, NULL);

这很完美,但我对基于文件的格式不满意;我想在 char* 变量中以纯二进制形式(即,没有 base64 或类似格式)保存我的密钥,并从中加载/保存密钥.这样我有更多的自由:我将能够将密钥直接存储到应用程序 const char key[] { 0x01, 0x02, ... };,通过网络套接字发送等

This works perfectly but I'm not happy with the file-based format; I want to save my key in pure binary form (ie, no base64 or similar) in a char* variable and load/save the key from/to it. This way I have much more freedom: I'll be able to store the key directly into the application const char key[] { 0x01, 0x02, ... };, send it over a network socket, etc.

不幸的是,虽然我还没有找到一种方法来做到这一点.我所知道的保存和加载密钥的唯一方法是直接将其读取/保存到文件中.

Unfortunately though I haven't found a way to do that. The only way to save and load a key I know of reads/saves it to a file directly.

推荐答案

使用 d2i_RSAPrivateKey 直接从包含二进制 DER 格式的缓冲区加载:

Use d2i_RSAPrivateKey to load directly from a buffer containing binary DER format:

const unsigned char *p = key;
RSA *r = d2i_RSAPrivateKey(NULL, &p, keylen);

相关文章