c - C中openssl RSA_public_encrypt()的段错误
问题描述
我一直在尝试使用 openssl 加密测试字符串,RSA_public_encrypt
但在我尝试运行它的所有方式中都会导致段错误。
我尝试使用 BIO 检查我从 pem 文件中读取的 RSA 密钥是否有效,并且它以正确的密钥和指数大小正确返回了公钥。
我最初尝试使用PEM_read_bio_RSA_PUBKEY
which 没有成功。我不完全确定 和 之间的区别PEM_read_bio_RSAPublicKey
,所以如果有人可以对此有所了解。
此外,在尝试之前,BIO
我使用了常规的 FILE 结构和与之对应的函数,它一直给我段错误,我也无法检查是否加载了正确的 RSA 密钥。不确定这是否相关。
#include <stdio.h>
#include <string.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/conf.h>
int main()
{
RSA *rsa;
rsa = RSA_new();
BIO *bp_public = NULL;
RSA *pubkey;
bp_public = BIO_new_file("public.pem", "rt");
pubkey = PEM_read_bio_RSAPublicKey(bp_public, &rsa, NULL, NULL);
BIO * keybio = BIO_new(BIO_s_mem());
RSA_print(keybio, rsa, 0);
char buffer [2048];
while (BIO_read (keybio, buffer, 2048) > 0)
{
printf("%s", buffer);
}
BIO_free(bp_public);
if (pubkey == NULL || rsa == NULL)
printf("Something went wrong");
char msg[] = "Hello";
unsigned char * encrypted = NULL;
RSA_public_encrypt(5, (unsigned char *)msg, encrypted, rsa, RSA_PKCS1_OAEP_PADDING);
printf("Here: %s", encrypted);
}
另外,我尝试同时使用pubkey
和rsa
作为键,但没有一个起作用。
我确信我错过了一些非常明显的东西,但我已经花了几个小时在后面,我现在有点迷失在 openssl 文档中。
谢谢您的帮助!
无关说明:如果我使用加密文本返回 nullRSA_private_encrypt()
解决方案
检查您是否正确管理各种 Openssl 资源。很多时候,可以释放的内容会受到限制。尽早释放资源可能会导致库中其他地方出现段错误。
推荐阅读
- javascript - Discord.js - 如何编辑 message.embed() 语句?
- python - 使用 C 绑定导入代码的 Pickle 模块
- node.js - 如何用玩笑模拟 AxiosInstance
- python - 如何将字典中的所有元素放入数据库
- pyspark - 在 Databricks 中使用 Spark API 连接到 ADLS
- arrays - 谷歌表格数组求和文本
- ruby-on-rails - 为什么我在尝试播种 csv 数据时看到此错误消息
- docker - docker-jenkins 容器无法访问互联网
- python - 将存储过程结果存储在数据框中时,MySql 命令不同步
- reactjs - 如何使用 React Native (Expo) 将文件/图像上传到 Azure Blob?