首页 > 解决方案 > C中openssl RSA_public_encrypt()的段错误

问题描述

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

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

我最初尝试使用PEM_read_bio_RSA_PUBKEYwhich 没有成功。我不完全确定 和 之间的区别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);
}

另外,我尝试同时使用pubkeyrsa作为键,但没有一个起作用。

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

谢谢您的帮助!

无关说明:如果我使用加密文本返回 nullRSA_private_encrypt()

标签: copensslrsa

解决方案


检查您是否正确管理各种 Openssl 资源。很多时候,可以释放的内容会受到限制。尽早释放资源可能会导致库中其他地方出现段错误。


推荐阅读