[openssl-users] Naive: how to generate EC public key from EC private key?

Dr. Stephen Henson steve at openssl.org
Thu Mar 17 23:45:38 UTC 2016


On Thu, Mar 17, 2016, Viktor Dukhovni wrote:

> 
> > On Mar 17, 2016, at 6:32 PM, Blumenthal, Uri - 0553 - MITLL <uri at ll.mit.edu> wrote:
> > 
> > Oh, and I'd much prefer to stay at the EVP level, rather than invoke BIO primitives for this task.
> 
> Well you can work with http://openssl.org/docs/manmaster/crypto/EC_KEY_key2buf.html
> to extract EC public key octets.

That's only available in the master branch, only encodes the key value and not
its parameters and of course it only works for EC.

> If you want an ASN.1 encoded "SPKI" object (i.e. an
> X509_PUBKEY in OpenSSL) then you can use
> 
> 	X509_PUBKEY *pk = NULL;
> 	unsigned char *buf = NULL;
> 	EVP_PKEY *key;
> 
> 	key = ... ; /* Get a keypair */
> 
> 	if (X509_PUBKEY_set(&pk, key) <= 0) {
> 		/* error */
> 	}
> 
> 	len = i2d_X509_PUBKEY(pk, &buf);
> 	if (len < 0 || buf == NULL) {
> 		/* error */
> 	}
> 	
> 	/* buf contains ASN.1-encoded SPKI, use it */
> 
> 	OPENSSL_free(buf);
> 	X509_PUBKEY_free(pk);
> 	EVP_PKEY_free(key); /* If no longer needed */
> 
> A shorter version of the above is possible via i2d_PUBKEY() which
> handles the creation, encoding and destruction of the intermediate
> X509_PUBKEY:
> 
>   int i2d_PUBKEY(EVP_PKEY *a, unsigned char **pp)
>   {
>     X509_PUBKEY *xpk = NULL;
>     int ret;
>     if (!a)
>         return 0;
>     if (!X509_PUBKEY_set(&xpk, a))
>         return 0;
>     ret = i2d_X509_PUBKEY(xpk, pp);
>     X509_PUBKEY_free(xpk);
>     return ret;
>   }
> 
> 

That's the preferred route as it uses the standard SubjectPublicKeyInfo
format and works with any supported public key type.

Steve.
--
Dr Stephen N. Henson. OpenSSL project core developer.
Commercial tech support now available see: http://www.openssl.org


More information about the openssl-users mailing list