簡體   English   中英

執行副總裁讀取PEM私鑰無法正常工作

[英]EVP reading PEM private key not working properly

當我運行以下代碼時,它會生成一個密鑰,將其寫入字符串,然后將其打印,將其讀入密鑰,然后針對OpenSSL_1_0_2e再次進行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);
}

在第二個輸出中,私鑰顯然太短了。 我究竟做錯了什么?

解決我特定問題的方法是,我試圖在EVP_PKEY上設置公鑰和私鑰,以為我需要同時加載它們才能將其用作密鑰對。 實際上,您僅加載兩者之一。 使用私鑰,可以導出公鑰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM