How can I get X and Y components from a ECC public key in PEM format without private key?

Viewed 772

I know we can use openssl to do that. However that requires the private key. In my case, I don't have the private key and only have the public key. I uses Google Cloud HSM and the private key is not accessible directly. I can only download the public key. Then how can I do it?

My public key, it uses secp256r1:

-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhspCFgsa/oSDJajb8DvaLhLURUbD
C2UXU1E/a//ht4NMLTadhSMc195SL8YD55tPXR6bvERBrZfYEmpBlkr8BQ==
-----END PUBLIC KEY-----
2 Answers

Is openssl required as the solution? I cannot see a way of getting the information you ask for that way.

I got this information via a simple Java program:

EC public key, 256 bits
  public x coord: 60967280926790184513158415212015267447322831299023265344568139622352475502467
  public y coord: 34455661551278605550386928620071510096611427884751984970963480406192147856389
  parameters: secp256r1 [NIST P-256, X9.62 prime256v1] (1.2.840.10045.3.1.7)

The Java code:

    String keyAsTxt = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhspCFgsa/oSDJajb8DvaLhLURUbDC2UXU1E/a//ht4NMLTadhSMc195SL8YD55tPXR6bvERBrZfYEmpBlkr8BQ==";
    byte[] keyAsBytes = Base64.getDecoder().decode(keyAsTxt);
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyAsBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("EC");
    PublicKey publicKey = keyFactory.generatePublic(keySpec);
    System.out.println(publicKey);

You could use:

openssl ec -pubin -noout -text -conv_form uncompressed

This will output:

Public-Key: (256 bit)
pub:
    04:86:ca:42:16:0b:1a:fe:84:83:25:a8:db:f0:3b:
    da:2e:12:d4:45:46:c3:0b:65:17:53:51:3f:6b:ff:
    e1:b7:83:4c:2d:36:9d:85:23:1c:d7:de:52:2f:c6:
    03:e7:9b:4f:5d:1e:9b:bc:44:41:ad:97:d8:12:6a:
    41:96:4a:fc:05
ASN1 OID: prime256v1
NIST CURVE: P-256

04 indicating it is uncompressed (we forced this), the X and Y coordinates are just concatenated behind each other:

X (hex): 86:ca:42:16:0b:1a:fe:84:83:25:a8:db:f0:3b:da:2e:12:d4:45:46:c3:0b:65:17:53:51:3f:6b:ff:e1:b7:83
Y (hex): 4c:2d:36:9d:85:23:1c:d7:de:52:2f:c6:03:e7:9b:4f:5d:1e:9b:bc:44:41:ad:97:d8:12:6a:41:96:4a:fc:05

A possible bash pipeline could be (would need to assure openssl text cli output is stable):

| grep -E "^ +.*" | tr -d ' \n' | sed 's/^...//' | sed 's/./ /96'
Related