gojwtecdsagolang-jwt

I am trying to create jwt token with ES256 algo, but I am not able to parse my private key


Here's my golang code where I am trying to create JWT token

package main

import (
    "encoding/pem"
    "fmt"
    "time"

    "github.com/dgrijalva/jwt-go"
)

func main() {
    // Sample PEM-encoded private key
    pemKey := `-----BEGIN EC PRIVATE KEY-----MHcCAQEEIAh5qA3rmqQQuu0vbKV/+zouz/y/Iy2pLpIcWUSyImSwoAoGCCqGSM49AwEHoUQDQgAEYD54V/vp+54P9DXarYqx4MPcm+HKRIQzNasYSoRQHQ/6S6Ps8tpMcT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg==-----END EC PRIVATE KEY-----`

    // Convert the PEM-encoded private key to a byte slice
    pemBytes, _ := pem.Decode([]byte(pemKey))
    // // Parse and decode the private key
    key, err := jwt.ParseECPrivateKeyFromPEM(pemBytes.Bytes)
    if err != nil {
        fmt.Println("Error parsing private key:", err)
        return
    }

    uAccessToken := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{
        "iss":         "issuer",
        "sub":         "access token",
        "exp":         time.Now().Add(time.Minute * 20).Unix(),
    })

    AccessToken, err := uAccessToken.SignedString(key); 
    if err != nil {
        fmt.Println("Error signing token:", err)
        return
    }

    // // You now have the ECDSA private key available in the 'key' variable

    fmt.Println("ECDSA Private Key:", AccessToken)
}

But I get this error everytime I try creating token:

Error parsing private key: Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key

Can anyone suggest what's going wrong in here?

I am trying to create JWT using ES256 algo where I needed Private key. But somehow I am getting error.


Solution

  • need two fixes

    1- comment/remove pem.Decode() it require raw pem key in bytes.

    2- key string in a single line change key string

    check solution here