1

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?

Christian Stewart
  • 15,217
  • 20
  • 82
  • 139
  • Majority of OpenSSL routines return something. You always must capture this value and compare with what you expect and throw if unexpected or failure is returned. – adlag Dec 20 '15 at 12:25
  • Code does not compile due to typo's – adlag Dec 20 '15 at 12:59
  • @adlag Code fixed. Also, I capture the results in the actual code.. Just the sample code I removed the error checking as it clutters up what I'm doing. All the functions return the success code. – Christian Stewart Dec 20 '15 at 17:25
  • Also see [How to generate RSA private key using openssl?](http://stackoverflow.com/a/30493975/608639) – jww Dec 21 '15 at 00:52

1 Answers1

2

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.

Christian Stewart
  • 15,217
  • 20
  • 82
  • 139