C EVP读取PEM私钥工作不正常

C EVP读取PEM私钥工作不正常,c,openssl,C,Openssl,当我运行以下代码时,它生成一个密钥,将其写入字符串,打印它,将其读入密钥,然后再次打印它,与OpenSSL\u 1\u 0\u 2e: #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/aes.h> #include <openssl/err.h> #include <openssl/rand.h> #define RSA_KEYLEN 2048 i

当我运行以下代码时,它生成一个密钥,将其写入字符串,打印它,将其读入密钥,然后再次打印它,与
OpenSSL\u 1\u 0\u 2e

#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include <openssl/rand.h>

#define RSA_KEYLEN 2048
int main()
{
  // Key generation
  EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
  EVP_PKEY* key = NULL;
  EVP_PKEY_keygen_init(ctx);
  EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, RSA_KEYLEN);
  EVP_PKEY_keygen(ctx, &key);
  EVP_PKEY_CTX_free(ctx);

  // Serialize to string
  unsigned char* keyStr;
  BIO *bio = BIO_new(BIO_s_mem());
  PEM_write_bio_PrivateKey(bio, key, NULL, NULL, 0, 0, NULL);
  int priKeyLen = BIO_pending(bio);
  keyStr = (unsigned char*)malloc(priKeyLen + 1);
  BIO_read(bio, keyStr, priKeyLen);
  keyStr[priKeyLen] = '\0';
  BIO_free_all(bio);

  // Print the string
  printf("%s", keyStr);

  // Reset the key
  EVP_PKEY_free(key);
  key = NULL;

  // Read from string
  bio = BIO_new(BIO_s_mem());
  BIO_write(bio, keyStr, priKeyLen);
  PEM_read_bio_PrivateKey(bio, &key, NULL, NULL);
  BIO_free_all(bio);

  // Free the string
  free(keyStr);

  // Serialize to string (again)
  bio = BIO_new(BIO_s_mem());
  PEM_write_bio_PrivateKey(bio, key, NULL, NULL, 0, 0, NULL);
  priKeyLen = BIO_pending(bio);
  keyStr = (unsigned char*)malloc(priKeyLen + 1);
  BIO_read(bio, keyStr, priKeyLen); 
  keyStr[priKeyLen] = '\0';
  BIO_free_all(bio);

  // Print string
  printf("%s", keyStr);
}
#包括
#包括
#包括
#包括
#包括
#定义RSA_KEYLEN 2048
int main()
{
//密钥生成
EVP_PKEY_CTX*CTX=EVP_PKEY_CTX_new_id(EVP_PKEY_RSA,NULL);
EVP_PKEY*key=NULL;
执行副总裁(ctx);
EVP_PKEY_CTX_set_rsa_keygen_bits(CTX,rsa_KEYLEN);
执行副总裁(ctx和钥匙);
免费执行副总裁(CTX);
//序列化为字符串
无符号字符*keyStr;
BIO*BIO=BIO_new(BIO_s_mem());
PEM_write_bio_PrivateKey(bio,key,NULL,NULL,0,0,NULL);
int priKeyLen=BIO_待定(BIO);
keyStr=(无符号字符*)malloc(priKeyLen+1);
BIO_读取(BIO、keyStr、priKeyLen);
keyStr[priKeyLen]='\0';
BIO_free_all(BIO);
//打印字符串
printf(“%s”,keyStr);
//重设钥匙
免费执行副总裁(钥匙);
key=NULL;
//从字符串读取
bio=bio_new(bio_s_mem());
BIO_写入(BIO、keyStr、priKeyLen);
PEM_read_bio_PrivateKey(bio,&key,NULL,NULL);
BIO_free_all(BIO);
//解开绳子
免费(keyStr);
//序列化为字符串(再次)
bio=bio_new(bio_s_mem());
PEM_write_bio_PrivateKey(bio,key,NULL,NULL,0,0,NULL);
priKeyLen=BIO_待定(BIO);
keyStr=(无符号字符*)malloc(priKeyLen+1);
BIO_读取(BIO、keyStr、priKeyLen);
keyStr[priKeyLen]='\0';
BIO_free_all(BIO);
//打印字符串
printf(“%s”,keyStr);
}

私钥在第二个输出中显然太短了。我做错了什么?

我的特殊问题的解决方案是,我试图在EVP_PKEY上设置公钥和私钥,认为我需要加载这两个密钥才能将其用作密钥对。实际上,您只加载其中一个。使用私钥,将派生公钥

大多数OpenSSL例程都会返回一些东西。您必须始终捕获该值,并与预期值进行比较,如果返回意外值或失败,则抛出该值。由于输入错误,代码无法编译s@adlag代码已修复。此外,我在实际代码中捕获结果。。只是我删除了错误检查的示例代码,因为它使我正在做的事情变得杂乱无章。所有函数都返回成功代码。另请参阅