c++ - 如何从包含多个密钥的文本文件中解析公钥
问题描述
我有一组要在代码中使用的公钥和私钥。两个密钥都存储在文件中,但公钥存储在一个文本文件中,其中第一行有“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,带有公钥:
最后,执行输出:
我想念的东西可能很明显,但是我不知道为什么会发生这种情况。
任何帮助都感激不尽。
解决方案
推荐阅读
- python - 使用python获取数据框中某些列(独立)的总数
- c# - 在 Windows 7 上使用带有 NSIS 的 Dotnet 失败
- node.js - 使用 Multer 和 Node 将多个文件上传到 mongoDB
- ssh - SSH Key 提示“ssh -Tv git@gitlab.tubit.tu-berlin.de”的密码
- android - Flutter:使用 InteractiveViewer 双击启用图像放大/缩小
- swift - 快速按顺序查找元素的计数?
- python - 使一个列表成为包含元素的字典
- python - 将正则表达式应用于 urlopen 请求
- python - Numpy:使用掩码为不同的行分配不同的值
- php - laravel mongodb 中不支持的投影选项