执行副总裁读取PEM私钥无法正常工作 [英] EVP reading PEM private key not working properly

查看:121
本文介绍了执行副总裁读取PEM私钥无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行以下代码时,它会生成一个密钥,将其写入字符串,进行打印,将其读入密钥,然后再次针对OpenSSL_1_0_2e进行打印:

When I run the following code, which generates a key, writes it to a string, prints it, reads it into the key, and prints it again, against OpenSSL_1_0_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);
}

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

The private key is obviously way too short in the second output. What am I doing wrong?

推荐答案

我特定问题的解决方案是我试图在EVP_PKEY上设置公钥和私钥,以为我需要同时加载它们才能将其用作密钥对.实际上,您仅加载两者之一.利用私钥,可以导出公钥.

The solution to my particular problem was I was trying to set the Public and Private key on the EVP_PKEY thinking that I needed to load both to use it as a keypair. Actually, you only load one of the two. With the private key, the public key is derived.

这篇关于执行副总裁读取PEM私钥无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆