Skip to content
This repository has been archived by the owner on May 21, 2022. It is now read-only.

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

Open
yongDataScince opened this issue Feb 9, 2021 · 4 comments

Comments

@yongDataScince
Copy link

`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 #65 (comment)

@BAN1ce
Copy link

BAN1ce commented Feb 15, 2021

SigningMethodES256 secret key must be an ecdsa.PrivateKey struct

type PrivateKey struct {
	PublicKey
	D *big.Int
}

@zsmhub
Copy link

zsmhub commented Jun 4, 2021

try jwt.SigningMethodES256 => jwt.SigningMethodHS256

@mattlopez4011
Copy link

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
Copy link

shadowshot-x commented Sep 23, 2021

@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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants