0

So I have a certificate in pem format (mycert.pem), from which I only need to extract the public key.

openssl x509 -in mycert.pem -pubkey -noout gives me a public key. However, it seems to be the base64 encoded string of the entire subject public key info.

Subject Public Key Info:
    Public Key Algorithm: id-ecPublicKey
        Public-Key: (256 bit)
        pub: 
            04:6e:af:3c:7d:4c:a3:1a:81:f0:ae:14:45:16:67:
            38:5b:09:4d:9e:55:f8:e2:f2:ba:e4:55:28:f6:31:
            d8:25:c3:2d:f9:a2:d5:62:ba:eb:17:5f:1d:ad:99:
            50:e4:a6:bd:eb:9b:44:18:0f:72:ae:bd:fb:87:1f:
            82:dd:98:be:25
        ASN1 OID: prime256v1
        NIST CURVE: P-256

However, I'm only interested in the "raw" public key part pub:

04:6e:af:3c:7d:4c:a3:1a:81:f0:ae:14:45:16:67:
38:5b:09:4d:9e:55:f8:e2:f2:ba:e4:55:28:f6:31:
d8:25:c3:2d:f9:a2:d5:62:ba:eb:17:5f:1d:ad:99:
50:e4:a6:bd:eb:9b:44:18:0f:72:ae:bd:fb:87:1f:
82:dd:98:be:25

How can I extract (dynamically!) the relevant information? It is important to have an approach that works for any certificate, not just the example presented.

My implementation is in php, so ideally I'll find a solution using phpseclib or openssl functions. But understanding how it works with openssl via the command line, for example, also helps. Thank you.

Leo
  • 1,508
  • 13
  • 27
  • What have you tried so far? What about [`openssl_pkey_get_public()`](https://www.php.net/manual/en/function.openssl-pkey-get-public.php) and [`openssl_pkey_get_details()`](https://www.php.net/manual/en/function.openssl-pkey-get-details.php)? The uncompressed raw public key is simply 0x04|x|y. – Topaco Oct 14 '21 at 08:56
  • @Topaco that's exactly what I am looking for. However, '0x04.$x.$y' is missing a leading zero. Can you explain to me if it's safe to just add a leading zero, or if there's a deeper logic behind it? – Leo Oct 14 '21 at 09:19
  • 2
    The format of an uncompressed raw public key is 0x04|x|y. For P-256, x has a size of 32 bytes. If x is smaller, prepend 0x00 values until this size is reached. The same applies to y. – Topaco Oct 14 '21 at 09:27
  • got it & thank you, that's exactly the answer I was looking for! – Leo Oct 14 '21 at 09:39

0 Answers0