JWT Signing Method HS256 Golang

4.7k Views Asked by At

I have a question about JWT signing with method HS256 in Go. I'm using this import "github.com/dgrijalva/jwt-go"

It doesn't require a secret key length >= 256 bits (32 bytes)?

Let's say I have an server application written in Golang which gives JWT signed with a secret key length of 16 bits. When I try to verify this JWT in the client application (that is written in Java) with the same secret key it gives me an error:

io.jsonwebtoken.security.WeakKeyException: The specified key byte array is 16 bits which is not secure enough for any JWT HMAC-SHA algorithm.

Well, this error makes sense since the secret key length is less than 256 bits, but how was it possible for the server application to generate a JWT signed with a secret key with a size less than 256 bits without giving an error?

Here is the function that creates the access token:

import(
    "time"

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

func CreateToken(userid uint64) (string, error) {
    var err error
    //Creating Access Token
    atClaims := jwt.MapClaims{}
    atClaims["authorized"] = true
    atClaims["user_id"] = userid
    atClaims["exp"] = time.Now().Add(time.Minute * 15).Unix()
    at := jwt.NewWithClaims(jwt.SigningMethodHS256, atClaims)
    token, err := at.SignedString([]byte("NRF"))
    if err != nil {
        return "", err
    }
    return token, nil
}
1

There are 1 best solutions below

3
Tim On

There is no "standard" jwt library in Go. So to answer this question thoroughly we will need to see the server code, or which library the server is using.

The crypto/hmac and crypto/hash packages don't define any errors to be returned in any case. So key length checking, like you described, should be done by the caller. So it is not a matter of the language go does something. It's a matter of how the program is written.

If you want to learn more, you can browse different implementations on https://jwt.io/#libraries-io. (Manually filter by Go).