Anisyanka
Anisyanka

Reputation: 63

Does private RSA, DSA or ECDSA key in pem-format contain public key?

I use hardcoded ec-kyes for testing my application. There is example for ecdsa:

const char pem_ecdsa_prv_key[] = {
    "-----BEGIN EC PRIVATE KEY-----\n"
    "MHcCAQEEIAGOaT3/9PJxSIFKPbvEhj61jY3CGPsgA46IVZlvIlnGoAoGCCqGSM49\n"
    "AwEHoUQDQgAE6Dw87+AYjRQzNsb3RmANmNENCZArERfCKZ5M9+2S/yomA6fmFdeb\n"
    "XNXeV066Nk4jnuwF1ZKqCBoMBjsnm0jlCw==\n"
    "-----END EC PRIVATE KEY-----\n"
};

const char pem_ecdsa_pub_key[] = {
    "-----BEGIN PUBLIC KEY-----\n"
    "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE6Dw87+AYjRQzNsb3RmANmNENCZAr\n"
    "ERfCKZ5M9+2S/yomA6fmFdebXNXeV066Nk4jnuwF1ZKqCBoMBjsnm0jlCw==\n"
    "-----END PUBLIC KEY-----\n"
};

It has been generated with help ssh-keygen utility. I need to convert this pem-strings to openssl EC_KEY format to use it with sign/verify openssl functions. I do conversion like this(error checking has been omitted):

EC_KEY *ecdsa = NULL;
BIO *bio= NULL;

/* read pem string to openssl bio format */
bio = BIO_new_mem_buf(pem_ecdsa_prv_key,sizeof(pem_ecdsa_prv_key));

/* convert bio to ec_key */
ecdsa = EC_KEY_new();
PEM_read_bio_ECPrivateKey(bio, &ecdsa, NULL, NULL);

Now I do this conversion for pem_ecdsa_prv_key and for pem_ecdsa_pub_key. Should i do this only for private key array, because it contains public key too?

Upvotes: 0

Views: 1122

Answers (1)

Shane Powell
Shane Powell

Reputation: 14148

You load the public key exactly the same way but you use the PEM_read_bio_EC_PUBKEY instead of PEM_read_bio_ECPrivateKey.

e.g.

/* read pem string to openssl bio format */
bio = BIO_new_mem_buf(pem_ecdsa_pub_key,sizeof(pem_ecdsa_pub_key));

/* convert bio to ec_key */
ecdsa = PEM_read_bio_EC_PUBKEY(bio, NULL, NULL, NULL);

(note, you don't need to allocate EC_KEY first in either the PEM_read_bio_EC_PUBKEY or PEM_read_bio_ECPrivateKey call)

Also, the private key normally contains the public key. If you load the private key, you can use the EC_KEY for all private key / public key usages. If you load the public key, you can only use it for public key usages.

Upvotes: 2

Related Questions