The specified key byte array is 136 bits which is not secure enough for any JWT HMAC-SHA algorithm.

本文介绍了如何在使用jjwt库时,由于秘钥过短引发的安全警告,并指导读者将JWT_SECRET字段长度增加到256位以符合JWT标准。通过修改`generateToken`方法,确保HMAC-SHA算法使用的秘钥足够安全。

场景

集合了<jjwt.version>0.11.5</jjwt.version>版本的 jwt

<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>${jjwt.version}</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>${jjwt.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
            <version>${jjwt.version}</version>
            <scope>runtime</scope>
        </dependency>

原 signWith 方法过时,更改后报错如下

主要错误信息如下

The specified key byte array is 136 bits which is not secure enough for any JWT HMAC-SHA algorithm.

2022-05-11 16:44:38.748 ERROR 83332 --- [io-13921-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/admin] threw exception [Request processing failed; nested exception is io.jsonwebtoken.security.WeakKeyException: The specified key byte array is 136 bits which is not secure enough for any JWT HMAC-SHA algorithm.  The JWT JWA Specification (RFC 7518, Section 3.2) states that keys used with HMAC-SHA algorithms 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#secretKeyFor(SignatureAlgorithm) method to create a key guaranteed to be secure enough for your preferred HMAC-SHA algorithm.  See https://tools.ietf.org/html/rfc7518#section-3.2 for more information.] with root cause

io.jsonwebtoken.security.WeakKeyException: The specified key byte array is 136 bits which is not secure enough for any JWT HMAC-SHA algorithm.  The JWT JWA Specification (RFC 7518, Section 3.2) states that keys used with HMAC-SHA algorithms 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#secretKeyFor(SignatureAlgorithm) method to create a key guaranteed to be secure enough for your preferred HMAC-SHA algorithm.  See https://tools.ietf.org/html/rfc7518#section-3.2 for more information.
	at io.jsonwebtoken.security.Keys.hmacShaKeyFor(Keys.java:96) ~[jjwt-api-0.11.5.jar:0.11.5]
	at com.admin.utils.JwtTokenUtils.generateToken(JwtTokenUtils.java:42) ~[classes/:na]
	at com.admin.service.AdminUserService.adminLogin(AdminUserService.java:59) ~[classes/:na]
	at com.admin.service.AdminUserService$$FastClassBySpringCGLIB$$1.invoke(<generated>) ~[classes/:na]
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.19.jar:5.3.19]
	at org.springframework.aop.framework.CglibAopProxy.invokeMethod(CglibAopProxy.java:386) ~[spring-aop-5.3.19.jar:5.3.19]
	at org.springframework.aop.framework.CglibAopProxy.access$000(CglibAopProxy.java:85) ~[spring-aop-5.3.19.jar:5.3.19]
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:704) ~[spring-aop-5.3.19.jar:5.3.19]
	at com.admin.service.AdminUserService$$EnhancerBySpringCGLIB$$1.adminLogin(<generated>) ~[classes/:na]
	at com.admin.controller.UserController.adminLogin(UserController.java:26) ~[classes/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_332]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_332]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_332]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_332]

解决

给下述代码中的JWT_SECRET字段弄长点,大概 256 来个字符的时候就可以了

    /**
     * 根据用户信息生成token
     */
    public String generateToken(String username) {

        Claims claims = Jwts.claims().setSubject(username);

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey key = Keys.hmacShaKeyFor(JWT_SECRET.getBytes(StandardCharsets.UTF_8));
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(key, signatureAlgorithm)
                .compact();
    }
ult-auth-plugin-2.4.0.jar!/com/alibaba/nacos/plugin/auth/impl/token/impl/JwtTokenManager.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: the length of secret key must great than or equal 32 bytes; And the secret key must be encoded by base64.Please see https://nacos.io/zh-cn/docs/v2/guide/user/auth.html at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:306) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:287) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:336) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:334) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:209) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1391) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:710) ... 99 common frames omitted Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: the length of secret key must great than or equal 32 bytes; And the secret key must be encoded by base64.Please see https://nacos.io/zh-cn/docs/v2/guide/user/auth.html at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:226) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117) at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:302) ... 112 common frames omitted Caused by: java.lang.IllegalArgumentException: the length of secret key must great than or equal 32 bytes; And the secret key must be encoded by base64.Please see https://nacos.io/zh-cn/docs/v2/guide/user/auth.html at com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager.processProperties(JwtTokenManager.java:80) at com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager.<init>(JwtTokenManager.java:66) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:213) ... 114 common frames omitted Caused by: java.lang.IllegalArgumentException: The specified key byte array is 128 bits which is not secure enough for any JWT HMAC-SHA algorithm. The JWT JWA Specification (RFC 7518, Section 3.2) states that keys used with HMAC-SHA algorithms MUST have a size >= 256 bits (the key size must be greater than or equal to the hash output size). See https://tools.ietf.org/html/rfc7518#section-3.2 for more information. at com.alibaba.nacos.plugin.auth.impl.jwt.NacosJwtParser.<init>(NacosJwtParser.java:49) at com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager.processProperties(JwtTokenManager.java:76) ... 120 common frames omitted 2025-06-23 15:26:44,333 WARN [ThreadPoolManager] Start destroying ThreadPool
06-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员鱼丸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值