Shocky2
Shocky2

Reputation: 556

How to get a string out of x509 certificate public key in go?

If I have an *x509.Certificate object, how can I extract the public key base64 string representation out of it?

Upvotes: 2

Views: 6514

Answers (1)

ifnotak
ifnotak

Reputation: 4662

NOTE: Jump to #3 if you already have the x509.Certificate object.


You would need to do the following:

  1. Decode the PEM with pem.Decode().
block, _ := pem.Decode([]byte(certPEM))
  1. Parse the certificate with x509.ParseCertificate().
cert, _ := x509.ParseCertificate(block.Bytes)
  1. Marshal the Public key with x509.MarshalPKIXPublicKey().
publicKeyDer, _ := x509.MarshalPKIXPublicKey(cert.PublicKey)
  1. Encode it in a PEM encoded structure with pem.EncodeToMemory().
publicKeyBlock := pem.Block{
    Type:  "PUBLIC KEY",
    Bytes: publicKeyDer,
}
publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))

Run it on Go Playground


You can confirm the result if you copy the certificate in the example to a file cert.pem with the command:

openssl x509 -inform pem -in cert.pem -pubkey -noout

You should get the same result!

Upvotes: 11

Related Questions