【问题标题】:How to get a string out of x509 certificate public key in go?如何在 go 中从 x509 证书公钥中获取字符串?
【发布时间】:2019-05-10 09:09:20
【问题描述】:

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

【问题讨论】:

  • 公钥由多个部分组成(RSA key 是两个数字;EC key 是曲线描述加上该曲线上的一个点),因此“ base64 字符串表示”。您可以为问题添加所需输出的示例吗?

标签: go base64 x509certificate x509


【解决方案1】:

注意:如果您已经拥有 x509.Certificate 对象,请跳转到 #3


您需要执行以下操作:

  1. 使用 pem.Decode() 解码 PEM。
block, _ := pem.Decode([]byte(certPEM))
  1. x509.ParseCertificate()解析证书。
cert, _ := x509.ParseCertificate(block.Bytes)
  1. 使用x509.MarshalPKIXPublicKey() 封送公钥。
publicKeyDer, _ := x509.MarshalPKIXPublicKey(cert.PublicKey)
  1. 使用 pem.EncodeToMemory() 将其编码为 PEM 编码结构。
publicKeyBlock := pem.Block{
    Type:  "PUBLIC KEY",
    Bytes: publicKeyDer,
}
publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))

Go Playground上运行它


如果您将示例中的证书复制到文件cert.pem,您可以使用以下命令确认结果:

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

你应该得到同样的结果!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 2018-01-27
    • 1970-01-01
    相关资源
    最近更新 更多