previouslyactualname
previouslyactualname

Reputation: 713

Read EC public key from .pem file in C

I generated a EC public and private key pair using:

openssl ecparam -name prime256v1 -genkey -noout -out ecprikey.pem
openssl ec -in ecprikey.pem -pubout -out ecpubkey.pem

I want to read the public key into a byte array in C. How do I go about it? Just read from the file? Or does OpenSSL provide something? THank you!

Upvotes: 4

Views: 8180

Answers (1)

jww
jww

Reputation: 102205

I want to read the public key into a byte array in C...

Well, the key on disk is likely PEM encoded. Because its a public key, it probably has the pre- and post- encapsulated boundaries of -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY-----. You can read it like that using standard library functions.

You can also read the public key with PEM_read_PUBKEY. The function returns a EVP_PKEY*. I believe you can convert the EVP_PKEY* to a EC_KEY* with:

EC_KEY* ecKey = EVP_PKEY_get1_EC_KEY(pKey);

The get1 above means the reference count on the key was bumped (as opposed to get0). Be sure to call EC_KEY_free when done with it.

I'm not sure how you would read the public key into an array given a EVP_PKEY* or EC_KEY*. At minimum, there are two pieces of information: the curve (like secp256k1) and the public element (a point on the curve, which consists of an (x,y) coordinate). If the named curve (i.e., the OID) is not present (i.e., the absence of the OPENSSL_EC_NAMED_CURVE flag), then you have all the domain parameters like p, a, b, G, etc. Perhaps you should look at an ASN.1/DER encoding. I think that's the closet you are going to get.

Upvotes: 3

Related Questions