gpt4 book ai didi

c - C 中 openssl RSA_public_encrypt() 上的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:48 26 4
gpt4 key购买 nike

我一直在尝试使用 openssl 的 RSA_public_encrypt 加密测试字符串,但在我尝试运行它的每一种方式中都会导致段错误。

我尝试使用 BIO 检查我从 pem 文件中读取的 RSA key 是否有效,它使用正确的 key 和指数大小正确地返回了公钥。

我最初尝试使用 PEM_read_bio_RSA_PUBKEY 但没有成功。我不完全确定它与 PEM_read_bio_RSAPublicKey 之间的区别,所以如果有人可以阐明这一点。

此外,在尝试 BIO 之前,我使用了常规的 FILE 结构和与之对应的函数,它一直给我段错误,我无法检查是否正确的 RSA key 是加载。不确定这是否相关。

#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);
}

此外,我尝试同时使用 pubkeyrsa 作为 key ,但均无效。

我确定我遗漏了一些非常明显的东西,但我已经花了几个小时在它后面,现在我有点迷失在 openssl 文档中。

感谢您的帮助!

不相关的注意事项:如果我使用 RSA_private_encrypt(),加密文本返回 null

最佳答案

来自 RSA_public_encrypt :

int RSA_public_encrypt(int flen, unsigned char *from,
unsigned char *to, RSA *rsa, int padding);

RSA_public_encrypt() encrypts the flen bytes at from (usually a session key) using the public key rsa and stores the ciphertext in to. to must point to RSA_size(rsa) bytes of memory.

但是你有 to 参数作为

unsigned char * encrypted = NULL;

也许你应该为它分配 RSA_size(rsa) 字节的内存:

unsigned char *encrypted = malloc(RSA_size(rsa));

关于c - C 中 openssl RSA_public_encrypt() 上的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53286960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com