openssl: Encoding of EC Public keys is broken
Using the new Encoder APIs to encode EC public keys seems to be broken.
Here is a reproducer:
#include <openssl/encoder.h>
#include <openssl/evp.h>
#include <openssl/ec.h>
#include <string.h>
#include <openssl/bio.h>
int main(void) {
EVP_PKEY *key = EVP_EC_gen("P-256");
unsigned char *publicKey = NULL;
size_t publicLen = 0;
BIO *out;
OSSL_ENCODER_CTX *ctx
= OSSL_ENCODER_CTX_new_for_pkey(key, EVP_PKEY_PUBLIC_KEY, "DER", NULL,
NULL);
if (ctx == NULL)
abort();
if (!OSSL_ENCODER_to_data(ctx, &publicKey, &publicLen))
abort();
OSSL_ENCODER_CTX_free(ctx);
BIO_dump_fp(stdout, publicKey, publicLen);
out = BIO_new_file("ecpubkey.der", "wb");
BIO_write(out, publicKey, publicLen);
printf("Success\n");
return 0;
}
Running this gives output like this:
0000 - 04 da 56 4c 0c 45 48 88-eb 4b ee a6 2a c1 47 61 ..VL.EH..K..*.Ga
0010 - f5 f9 9d 84 4e a2 42 59-0d c6 77 94 e2 2b 5a 8c ....N.BY..w..+Z.
0020 - 31 8a 42 fc 4a a2 76 5c-99 64 5d 5b bb c5 00 8c 1.B.J.v\.d][....
0030 - fb 94 f0 06 7a d3 dc 1e-06 76 46 d7 00 d1 42 09 ....z....vF...B.
0040 - 08 .
Success
With the output in a file “ecpubkey.der”. Trying to use that output file fails:
$ openssl ec -in ecpubkey.der -pubin -inform DER
read EC key
Could not read public key from ecpubkey.der
unable to load Key
Inspecting the DER is also interesting:
$ openssl asn1parse -in ecpubkey.der -inform DER
Error in encoding
4007080A647F0000:error:0680007B:asn1 encoding routines:ASN1_get_object:header too long:crypto/asn1/asn1_lib.c:105:
Modifying the above reproducer to change the string “DER” to “PEM”, gives out an output file like this:
-----BEGIN EC PUBLIC KEY-----
BMzAylbS4lDBJFEMSMf6ZnnBqcHyP6ERRK1jwlJ6/3he0XP0QDPyOb981WxU3BcZ
4/m9TUWdk7TN/P8d6o8khak=
-----END EC PUBLIC KEY-----
Which has a PEM header of “EC PUBLIC KEY” so this means it contains a …wait…what??? Is there such a thing as an “EC PUBLIC KEY” file??? Don’t we just use SPKI format for EC public keys???
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 28 (17 by maintainers)
Commits related to this issue
- Fix DER encoder implementations for output structures "EC" and "SM2" These DER encoder implementations are supposed to be aliases for the "type-specific" output structure, but were made different in ... — committed to levitte/openssl by levitte 3 years ago
- Fix DER encoder implementations for output structures "EC" and "SM2" These DER encoder implementations are supposed to be aliases for the "type-specific" output structure, but were made different in ... — committed to levitte/openssl by levitte 3 years ago
For 3.0, should we just not have any support for type-specific encoding of public EC keys? It doesn’t really make any sense. Presumably the “NULL” output structure means “any”, and so I would have expected to get SubjectPublicKeyInfo as the output.
Perhaps just leave the i2d_PublicKey() behaviour with EC keys alone. Its weird and wrong, but people might be relying on it.