0

There is an application that creates a base64 encoded public key with the following commands:

openssl ecparam -genkey -name prime256v1 -out ecdsa.pem
openssl ec -noout -text -conv_form compressed -in ecdsa.pem | grep '^pub:' -A 3 | tail -n 3 | tr -d ' \n:' | xxd -r -p | base64

How do I use this public key in Java? According to my research it should work with this code, but I get an exception that the key is too long:

EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode("base64-from-above");
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
NoobieNoob
  • 887
  • 2
  • 11
  • 31
  • The Java code expects a key in X.509/SPKI format. The key generated with OpenSSL is a compressed public key. Both are different formats, so a conversion is necessary. Can you use BouncyCastle? Regarding an example, what do you need the key for, ECDH or ECDSA? Can you post an example key just to be sure? – Topaco Apr 03 '21 at 15:45
  • Just execute the commands above. Example: A0rMwyEJQnTGfW9Wcx60sNS3X1xS9Th5Wsz3519Kacw7 – NoobieNoob Apr 03 '21 at 16:01
  • I need it for ECDSA and BouncyCastle is possible I think. Thanks so far! – NoobieNoob Apr 03 '21 at 16:01
  • Mostly dupe https://stackoverflow.com/questions/52232996/nodejs-crypto-ecdh-publickey-hex-as-x-509 and more linked there – dave_thompson_085 Apr 03 '21 at 18:28

0 Answers0