3

I met this issue and really do not know how to resolve it, can anyone help to provide a working solution?

func GenerateJWT(name, role string) (string, error)  {
    //create a singner for rsa 256
    claims := &jwt.StandardClaims{
        ExpiresAt: 15000,
        Issuer:    "test",
    }

    token :=jwt.NewWithClaims(jwt.SigningMethodES256, claims)
    log.Println("generated toke is ")
    log.Println(token)
    tokenString, err := token.SignedString([]byte("secret"))
....
}

Now I am alway having:

key is of invalid type

error. I google a lot, and even for jwt-go library it self, they are providing exactly same solution, but why I kept having the

key is of invalid type

error?

Can anyone help to provide a working sample about how to generate jwt token in go?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user3006967
  • 3,291
  • 10
  • 47
  • 72

1 Answers1

10

From the README:

The ECDSA signing method (ES256,ES384,ES512) expect *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for validation

So use an elliptic curve key:

package main

import (
        "crypto/ecdsa"
        "crypto/elliptic"
        "crypto/rand"
        "log"

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

func main() {
        key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
        if err != nil {
                log.Fatal(err)
        }

        claims := &jwt.StandardClaims{
                ExpiresAt: 15000,
                Issuer:    "test",
        }

        token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)

        tokenString, err := token.SignedString(key)
        if err != nil {
                log.Fatal(err)
        }

        log.Println(tokenString)
}

To store the generated key for later use with jwt.ParseECPrivateKeyFromPEM and jwt.ParseECPublicKeyFromPEM:

import (
        "crypto/ecdsa"
        "crypto/x509"
        "encoding/pem"
)

func pemKeyPair(key *ecdsa.PrivateKey) (privKeyPEM []byte, pubKeyPEM []byte, err error) {
        der, err := x509.MarshalECPrivateKey(key)
        if err != nil {
                return nil, nil, err
        }

        privKeyPEM = pem.EncodeToMemory(&pem.Block{
                Type:  "EC PRIVATE KEY",
                Bytes: der,
        })

        der, err = x509.MarshalPKIXPublicKey(key.Public())
        if err != nil {
                return nil, nil, err
        }

        pubKeyPEM = pem.EncodeToMemory(&pem.Block{
                Type:  "EC PUBLIC KEY",
                Bytes: der,
        })

        return
}
Peter
  • 29,454
  • 5
  • 48
  • 60