Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract public key from EVP_PKEY keypair?

I am implementing an encryption / decryption scheme in my application using OpenSSL's high-level EVP_*() functions, so I can easily switch the actual algorithms used without having to change the API calls.

I can create a key pair with relative ease:

// dumbed down, no error checking for brevity
EVP_PKEY * pkey;
// can change EVP_PKEY_RSA to something else here
EVP_PKEY_CTX * context = EVP_PKEY_CTX_new_id( EVP_PKEY_RSA, NULL );
EVP_PKEY_keygen_init( ctx );
// could set parameters here
EVP_PKEY_keygen( context, &pkey );
// ...
EVP_PKEY_CTX_free( context );

pkey now holds a key pair, i.e. both secret and public key. That's fine for the secret side of things, but obviously I would like to extract only the public key component for use on the public side of things.

I was able to find RSA-specific functions, but nothing using the high-level EVP_*() API.

Help?

like image 890
DevSolar Avatar asked Aug 27 '14 13:08

DevSolar


1 Answers

You could use following methods to separate public key and private key for future use.

int PEM_write_bio_PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc,
                    unsigned char *kstr, int klen,
                    pem_password_cb *cb, void *u);

 int PEM_write_PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc,
                    unsigned char *kstr, int klen,
                    pem_password_cb *cb, void *u);
EVP_PKEY *PEM_read_bio_PUBKEY(BIO *bp, EVP_PKEY **x,
                    pem_password_cb *cb, void *u);

 EVP_PKEY *PEM_read_PUBKEY(FILE *fp, EVP_PKEY **x,
                    pem_password_cb *cb, void *u);

 int PEM_write_bio_PUBKEY(BIO *bp, EVP_PKEY *x);
 int PEM_write_PUBKEY(FILE *fp, EVP_PKEY *x);

For detailed information, please refer to <openssl/pem.h>.

like image 99
Jared Avatar answered Sep 29 '22 22:09

Jared