Reputation: 556
If I have an *x509.Certificate
object, how can I extract the public key base64 string representation out of it?
Upvotes: 2
Views: 6514
Reputation: 4662
NOTE: Jump to #3 if you already have the x509.Certificate
object.
You would need to do the following:
pem.Decode()
.block, _ := pem.Decode([]byte(certPEM))
x509.ParseCertificate()
.cert, _ := x509.ParseCertificate(block.Bytes)
x509.MarshalPKIXPublicKey()
.publicKeyDer, _ := x509.MarshalPKIXPublicKey(cert.PublicKey)
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