首页 > 解决方案 > 如何从包含多个密钥的文本文件中解析公钥

问题描述

我有一组要在代码中使用的公钥和私钥。两个密钥都存储在文件中,但公钥存储在一个文本文件中,其中第一行有“id : {a number}”,然后从第二行开始是公钥。

我试图编写一个函数来解析文件并返回一个 RSA 指针(RSA *)。它通过读取文件的第一行并忽略它来工作,只是为了移动文件指针,然后我pub_key=PEM_read_RSAPublicKey(fp,NULL,NULL,NULL);用来填充 pub_key 并返回它。

这是我的函数调用pub_key = parse_pubkey_from_common_file("encryption/1.id");,这是我的函数:

RSA *parse_pubkey_from_common_file(char *filepath)
{
RSA *pub_key=NULL;
FILE *fp=NULL;
size_t len = 0;
size_t nread = 0;

char *line = NULL;
fp = fopen(filepath, "rt");
bool first=true;

while ((int)(nread = getline(&line, &len, fp)) != -1)
{
    line[nread-1] = '\0';   //  get rid of the "\n"
    std::cout << "line = " <<line << "length = "<<nread<< std::endl;
    if (first)
        break;      
}

free(line);
pub_key = PEM_read_RSAPublicKey(fp,NULL,NULL,NULL);
if (pub_key!=NULL)
{
    fprintf(stderr,"Public key read.\n");
}

BIO * keybio = BIO_new(BIO_s_mem());
RSA_print(keybio, pub_key, 0);
char buffer [1024];
std::string res = "";
while (BIO_read (keybio, buffer, 1024) > 0)
{
    std::cout << buffer;
}
BIO_free(keybio); //appropriate free "method"
fclose(fp);
std::cout << "------------------ from the original file ------------------" << '\n';
fp = fopen("encryption/public.pem", "rt");
pub_key = PEM_read_RSAPublicKey(fp,NULL,NULL,NULL);
if (pub_key!=NULL)
{
    fprintf(stderr,"Public key read.\n");
}

keybio = BIO_new(BIO_s_mem());
RSA_print(keybio, pub_key, 0);
res = "";
while (BIO_read (keybio, buffer, 1024) > 0)
{
    std::cout << buffer;
}
BIO_free(keybio); //appropriate free "method"

unsigned int cipher_size=RSA_size(pub_key);
std::cout << "cipher_size is: "<< cipher_size << '\n';
fclose(fp);

return pub_key;
}

从“std::cout ---- from the original file -----”和下面的代码可以做同样的事情,但使用带有公钥的原始 (.pem) 文件。

当我运行此部分注释掉的函数时,我无法正确使用返回的 RSA *。但是当它运行并覆盖上面的变量时,我以后可以正确使用它而没有问题。

我还尝试打印我阅读的内容以找到任何差异,但没有任何差异。

这是我使用的文件和执行的屏幕截图:

执行期间访问的第一个文件,其中包含 id: {a number} 第一张截图

第二个文件未经编辑的.pem,带有公钥: 第二张截图

最后,执行输出: 第三张截图

我想念的东西可能很明显,但是我不知道为什么会发生这种情况。

任何帮助都感激不尽。

标签: c++parsingopenssl

解决方案


推荐阅读