duanjing1023 2017-07-28 15:20
浏览 2750
已采纳

GO-如何将公钥从字符串转换为PEM格式

I am trying to use jwt library to do jwt validation. And i am getting public key from another application by calling its REST endpoint which is returning public key in string format.

So now when trying to send that public key in same string format, i am getting "Invalid key format". Any help on how to convert string formatted key to a valid PEM format would be great.

func (test *TESTStrategy) doJWTValidation(token string, key string, logger *util.Logger) (TESTResponse, error) {
    parsedToken, jwtErr := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
        return decodedJWT.ParsedPubKey, nil
    })

Below is the error what i am getting when passing key as a string to jwt.Pasrse() call.

enter image description here

Public Key: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsFWkb/eSl6I3DRVhaonW3DFy8EnL0yaPiDzCcOLuYfBjN9zZIR1wXmnMJFle1K89qHGg42wgweVTIwA1XFTfoUKSziwsjF6FscZX5H56ZYyS/wWiO3rWWynlfbSZt+ga71+ndsu+A0Dy7Nn7ZgP8kRsu4UM5vE7QQTRERNiUKpzScN1cgZUFUqSddQmkwTEN8hH1mFX1Mum54NGqWIlmQxQDrOyogmMXIaaakhabcmuIPMULVVDVwUJC9sSDsc/j05qcZn3kkiEBRyiYB6ZLY2W7WfiV+dB7/icPONsYSD0FxHWEGNnbqtiGoNf9WZWtaP+o8WMR9sB3GKGVnbLvbQIDAQAB

  • 写回答

1条回答 默认 最新

  • duanhuo3392 2017-07-28 16:08
    关注

    That's a PEM encoded key, it's just missing the BEGIN & END headers. The key is simple Base64 encoded, you can decode and unmarshal into a RSA key as follows:

    base64Data := []byte(`MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsFWkb/eSl6I3DRVhaonW3DFy8EnL0yaPiDzCcOLuYfBjN9zZIR1wXmnMJFle1K89qHGg42wgweVTIwA1XFTfoUKSziwsjF6FscZX5H56ZYyS/wWiO3rWWynlfbSZt+ga71+ndsu+A0Dy7Nn7ZgP8kRsu4UM5vE7QQTRERNiUKpzScN1cgZUFUqSddQmkwTEN8hH1mFX1Mum54NGqWIlmQxQDrOyogmMXIaaakhabcmuIPMULVVDVwUJC9sSDsc/j05qcZn3kkiEBRyiYB6ZLY2W7WfiV+dB7/icPONsYSD0FxHWEGNnbqtiGoNf9WZWtaP+o8WMR9sB3GKGVnbLvbQIDAQAB`)
    d := make([]byte, base64.StdEncoding.DecodedLen(len(base64Data)))
    n, err := base64.StdEncoding.Decode(d, base64Data)
    if err != nil {
        // Handle error
    }
    d = d[:n]
    key,err:=x509.ParsePKIXPublicKey(d)
    if err != nil {
        // Handle error
    }
    fmt.Println(key)
    

    If you need the key in PEM encoded form, simple add the appropriate header and footer, e.g. -----BEGIN PUBLIC KEY----- & -----END PUBLIC KEY-----. Note that the BEGIN header must start on its own line and end in a new line (" "). The END header must also be proceeded by a new line.

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

报告相同问题?

悬赏问题

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