dgrijalva / jwt-go

ARCHIVE - Golang implementation of JSON Web Tokens (JWT). This project is now maintained at:
https://github.com/golang-jwt/jwt
MIT License
10.78k stars 997 forks source link

key is of invalid type, []byte('key') - not working. Hello from 2021... #452

Open yongDataScince opened 3 years ago

yongDataScince commented 3 years ago

`token := jwt.NewWithClaims(jwt.SigningMethodES256, &tokenClaims{ jwt.StandardClaims { ExpiresAt: time.Now().Add(tockenTTL).Unix(), IssuedAt: time.Now().Unix(), }, user.ID, })

signKey := []byte("kdnjsndjnd*jdnj212md")

tkn, err := token.SignedString(signKey)
return tkn, err`

Originally posted by @yongDataScince in https://github.com/dgrijalva/jwt-go/issues/65#issuecomment-776227353

BAN1ce commented 3 years ago

SigningMethodES256 secret key must be an ecdsa.PrivateKey struct

type PrivateKey struct {
    PublicKey
    D *big.Int
}
zsmhub commented 3 years ago

try jwt.SigningMethodES256 => jwt.SigningMethodHS256

mattlopez4011 commented 3 years ago

This is how I was able to solve the "key is invalid" error for ES256 encryption:

` privateKey := "YOU-PRIVATE-KEY"

atClaims := jwt.MapClaims{}
atClaims["exp"] = json.Number(strconv.FormatInt(time.Now().Add(time.Minute*15).Unix(), 10))
atClaims["aud"] = "Audience" // OPTIONAL AUDIENCE 

token := jwt.NewWithClaims(jwt.SigningMethodES256, atClaims)
token.Header["kid"] = "KEY-IDENTIFIER"

block, _ := pem.Decode([]byte(privateKey))

key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
fmt.Println("Error parsing private key ", err.Error())
    return "", err
}

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

fmt.Println("signedToken: ", signedToken)`
shadowshot-x commented 2 years ago

@zsmhub is correct. HS256 can take a simple string input as secret. However, the ES256 expects a parsed secret key. As ECDSA is used with SHA in this case, it requests a string parsed in ECDSA Private Key format. This can be done as @mattlopez4011 mentioned with x509.ParsePKCS8PrivateKey.

https://pkg.go.dev/crypto/x509#ParsePKCS8PrivateKey