dtj2ww9500 2019-05-10 09: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 10: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().
    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!

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?