如何在Go中从x509证书公钥中获取字符串?
问题描述:
If I have an *x509.Certificate
object, how can I extract the public key base64 string representation out of it?
如果我有一个 * x509.Certificate code>对象,如何提取公钥 base64字符串表示出来了吗? p>
div>
答
NOTE: Jump to #3 if you already have the x509.Certificate
object.
You would need to do the following:
- Decode the PEM with
pem.Decode()
.
block, _ := pem.Decode([]byte(certPEM))
- Parse the certificate with
x509.ParseCertificate()
.
cert, _ := x509.ParseCertificate(block.Bytes)
- Marshal the Public key with
x509.MarshalPKIXPublicKey()
.
publicKeyDer, _ := x509.MarshalPKIXPublicKey(cert.PublicKey)
- 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!