Venkat
Venkat

Reputation: 81

GO - How to convert public key from string to PEM format

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

Upvotes: 0

Views: 18656

Answers (1)

Martin Campbell
Martin Campbell

Reputation: 1798

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 ("\n"). The END header must also be proceeded by a new line.

Upvotes: 4

Related Questions