JWT设置密钥长度

一、问题描述

 我需要用调用这个系统本来就有的鉴权代码,然后让用户进行登录,但是在走JWT自动创建Token的时候,就开始报错了。报错信息如下:

io.jsonwebtoken.security.WeakKeyException: The signing key's size is 40 bits which is not secure enough for the HS256 algorithm.  The JWT JWA Specification (RFC 7518, Section 3.2) states that keys used with HS256 MUST have a size >= 256 bits (the key size must be greater than or equal to the hash output size).  Consider using the io.jsonwebtoken.security.Keys class's 'secretKeyFor(SignatureAlgorithm.HS256)' method to create a key guaranteed to be secure enough for HS256.  See https://tools.ietf.org/html/rfc7518#section-3.2 for more information.

大概意思就是密钥的值太少了,以至于不符合这个HS256的规定。

二、问题解决

   public static Token createJWT(Map<String, String> user, long expire) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //生成签名密钥
        byte[] apiKeySecretBytes = Base64.getDecoder().decode(BASE64_SECURITY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        System.out.println(signingKey);
        System.out.println(signatureAlgorithm);
        System.out.println(signatureAlgorithm.getJcaName());
        //添加构成JWT的类
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JsonWebToken")
                .signWith(signatureAlgorithm, signingKey);

        //设置JWT参数
        user.forEach(builder::claim);

        //添加Token过期时间
        long expMillis = nowMillis + expire * 1000;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp).setNotBefore(now);

        // 组装Token信息
        Token tokenInfo = new Token();
        tokenInfo.setToken(builder.compact());
        tokenInfo.setExpire(expire);
        tokenInfo.setExpiration(exp);
        return tokenInfo;
    }

报错的信息是在添加JWT的类的时候,

signatureAlgorithm,signingKey 只有这两个是变量。

但是signatureAlgorithm这个打印出来是算法的名字HS256,signingKey 这个是密钥,而错误信息提示的也是它。所以我们就点进去,然后会发现有一个签名。


    /**
     * JWT token 签名
     */
    public static final String JWT_SIGN_KEY = "ceres";

我们尝试把它设置长一点


    /**
     * JWT token 签名
     */
    public static final String JWT_SIGN_KEY = "cereshuzhitingnizhenbangcereshuzhitingnizhenbang";

然后再走代码就可以走通了。、

三、问题总结

这个BUG找的挺长时间的,用了差不多一个上午的时间,在开始找的时候,因为我也是第一次接触JWT,所以也不会知道会有密钥签名。但是我感觉别人写的代码也没有问题,所以我就在自己写的代码就开始找,但是我写的代码,我真的找不出错。所以就耗费了这么长时间,所以总结出,当确认自己的代码没问题的时候,该怀疑其他人的怀疑,没有什么事情是决定的。

猜你喜欢

转载自blog.csdn.net/MyxZxd/article/details/109728302
今日推荐