简体   繁体   English

如何在Go中从x509证书公钥中获取字符串?

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

如果我有一个*x509.Certificate对象,如何从中提取公钥base64字符串表示形式?

NOTE: Jump to #3 if you already have the x509.Certificate object. 注意:如果您已经具有x509.Certificate对象,请跳至#3


You would need to do the following: 您需要执行以下操作:

  1. Decode the PEM with pem.Decode() . 使用pem.Decode()解码PEM。
block, _ := pem.Decode([]byte(certPEM))
  1. Parse the certificate with x509.ParseCertificate() . 使用x509.ParseCertificate()解析证书。
cert, _ := x509.ParseCertificate(block.Bytes)
  1. Marshal the Public key with x509.MarshalPKIXPublicKey() . 使用x509.MarshalPKIXPublicKey()将公钥x509.MarshalPKIXPublicKey()
publicKeyDer, _ := x509.MarshalPKIXPublicKey(cert.PublicKey)
  1. Encode it in a PEM encoded structure with pem.EncodeToMemory() . 使用pem.EncodeToMemory()编码为PEM编码的结构。
publicKeyBlock := pem.Block{
    Type:  "PUBLIC KEY",
    Bytes: publicKeyDer,
}
publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))

Run it on Go Playground Go Playground上运行


You can confirm the result if you copy the certificate in the example to a file cert.pem with the command: 如果使用以下命令将示例中的证书复制到文件cert.pem ,则可以确认结果:

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

You should get the same result! 您应该得到相同的结果!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM