JWT遇到的一些BUG

发布于:2025-02-10 ⋅ 阅读:(51) ⋅ 点赞:(0)

 The signing key's size is 240 bits which is not secure enough for the HS256 algorithm

io.jsonwebtoken.security.WeakKeyException: The signing key's size is 240 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.

翻译:

io.jsonwebtoken.security.WeakKeyException: 签名密钥长度为240位,不符合HS256算法的安全要求。根据JWT JWA规范(RFC 7518 第3.2节),HS256算法使用的密钥长度必须≥256位(密钥尺寸必须大于或等于哈希输出长度)。建议使用io.jsonwebtoken.security.Keys类的'secretKeyFor(SignatureAlgorithm.HS256)'方法生成符合HS256安全标准的密钥。详细信息请参阅:https://tools.ietf.org/html/rfc7518#section-3.2。

出现这个说明是密钥的长度不够, 不符合安全要求。一个字节8位,因此256位需要32个字节,因此密钥的长度要大于等于32位才能符合要求。

下面提供的代码中的签名是abcdefghijklmnopqrstuvwxyzABCDEFG是33位,符合要求

如果写成“abcdefghijklmnopqrstuvwxyzABCDE”就是31位,少于32位,会报错,有兴趣的可以试验一下。

@Test
public void JwtTest()
{
    String enconde=Encoders.BASE64.encode("abcdefghijklmnopqrstuvwxyzABCDEFG".getBytes());
    System.out.println(enconde);

    Map<String,Object>Claims=new HashMap<>();
    Claims.put("id",1);
    Claims.put("username","qixia");

    String jwt= Jwts.builder().signWith(SignatureAlgorithm.HS256,enconde).addClaims(Claims)
            .setExpiration(new Date(System.currentTimeMillis()+60*1000)).compact();
    System.out.println(jwt);

}

io.jsonwebtoken.lang.UnknownClassException

io.jsonwebtoken.lang.UnknownClassException: Unable to load class named [io.jsonwebtoken.impl.DefaultJwtBuilder] from the thread context, current, or system/application ClassLoaders.  All heuristics have been exhausted.  Class could not be found.  Have you remembered to include the jjwt-impl.jar in your runtime classpath?

翻译:

io.jsonwebtoken.lang.UnknownClassException: 无法从线程上下文(thread context)、当前类加载器或系统/应用类加载器(system/application ClassLoaders)中加载名为 [io.jsonwebtoken.impl.DefaultJwtBuilder] 的类。所有可能的加载途径均已尝试,但未能找到该类。请确认运行时类路径(runtime classpath)中是否包含 jjtt-impl.jar。 

说明没有引入 jjwt-impl,在pom.xml添加下面的依赖,注意添加好后要重新加载pom.xml

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.12.5</version>
</dependency>