dtj2ww9500 2019-05-10 01:09
浏览 1768
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • dongzhuo8210 2019-05-10 02:13
    关注

    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().
    1. publicKeyBlock := pem.Block{
    2. Type: "PUBLIC KEY",
    3. Bytes: publicKeyDer,
    4. }
    5. 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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部