1
votes

I get a InvalidKeyException: invalid key format when creating a java.security.PublicKey from a PEM file generated by openssl ec -pubout .... The same code works for RSA keys. What am I doing wrong?

The public key reads:

-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAG0FCGgyhUeJYUXeXoiKOU4GiyTORZ
U9+OpadxpVWqPbNoSNcfK7Ea13eWOKXlUe22v4Clce3t5nrCEBkwqhhe/g==
-----END PUBLIC KEY-----

EC key generation with OpenSSL:

openssl ecparam -genkey -out private_key.pem -outform PEM -name prime256v1
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
openssl ec -in private_key.pem -inform PEM -out public_key.pem -outform PEM -pubout

(I already tried different settings for conv_form and param_enc)

Java code:

KeyFactory kf = KeyFactory.getInstance("EC");

byte[] privEncoded = ... // read from private_key.der file
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privEncoded);
PrivateKey privKey = kf.generatePrivate(privSpec);

byte[] pubEncoded = .... // read from public_key.pem file
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
PublicKey pubKey = kf.generatePublic(pubSpec); // <-- InvalidKeyException

Edit: Contrary to what I said above, reading the RSA public key now fails too when trying it with a newly generated PEM. Also, encrypting and then decrypting fails. Stripping the BEGIN and END line from the PEM and converting Base64 to byte, as suggested by GregS, solved it!

1

1 Answers

0
votes

The so-called "PEM" format is not supported by Java. You must either save the data in openssl's "DER" format or strip out the first and last lines and decode the base64 in your Java program. See javax.xml.bind.DataTypeConverter.parseBase64Binary to go from base64 to bytes.