Search code examples
encryptionopensslpublic-key

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


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-----

Solution

  • 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:

    Curve Name: secp256r1 [NIST P-256,X9.62 prime256v1] (1.2.840.10045.3.1.7)
    Public Key X Coordinate (hex): c015519931128efe3dfd267250c4f9547dd0d6ac39823e0e5581212020210976
    Public Key Y Coordinate (hex): 771433a3cdbb28a7a0522038af4aee45d43d0226439ca752db416eea21ad6076
    

    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);
    
    if (publicKey instanceof ECPublicKey) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        String xCoord = ecPublicKey.getW().getAffineX().toString(16);
        String yCoord = ecPublicKey.getW().getAffineY().toString(16);
    
        ECParameterSpec ecSpec = ecPublicKey.getParams();
        String curveName = ecSpec.toString(); // This will give you the curve parameters
    
        System.out.println("Curve Name: " + curveName);
        System.out.println("Public Key X Coordinate (hex): " + xCoord);
        System.out.println("Public Key Y Coordinate (hex): " + yCoord);
    }