先看报错:
java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1039)
at javax.crypto.Cipher.implInit(Cipher.java:805)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1396)
at javax.crypto.Cipher.init(Cipher.java:1327)
at com.xyhlw.wechat.utils.WxBizMsgCrypt.decrypt(WxBizMsgCrypt.java:159)
at com.xyhlw.wechat.utils.WxBizMsgCrypt.decryptMsg(WxBizMsgCrypt.java:251)
at com.xyhlw.wechat.service.impl.ThirdPartyPlatformWechatAuthEventServiceImpl.getTiket(ThirdPartyPlatformWechatAuthEventServiceImpl.java:198)
at com.xyhlw.wechat.service.impl.ThirdPartyPlatformWechatAuthEventServiceImpl.authEvent(ThirdPartyPlatformWechatAuthEventServiceImpl.java:124)
at com.xyhlw.wechat.controller.ThirdPartyPlatformWechatCallbackController.getTicket(ThirdPartyPlatformWechatCallbackController.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
2024-10-05 16:21:55.739 INFO 14388 --- [nio-8090-exec-1] dPartyPlatformWechatAuthEventServiceImpl : 事件信息获取tiket 失败null
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
2024-10-05 16:21:55.739 INFO 14388 --- [nio-8090-exec-1] dPartyPlatformWechatAuthEventServiceImpl : 没有获取到tiket......
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:346)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:887)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1684)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
java.security.InvalidKeyException: Illegal key size 这个错其实一看就知道啥问题了,key的长度超出了限制,但是非常奇怪好几年以前的代码,而且现在还稳定在线上跑着的代码突然就不行了非常离谱,首先就排查了肯定不是代码问题,那是啥问题?
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
/**
* 针对org.apache.commons.codec.binary.Base64,
* 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本)
* 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi
*/
package com.xyhlw.wechat.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.Arrays;
/**
* <p>
* 提供接收和推送给公众平台消息的加解密接口(UTF8编码的字符串).
* @author yangchang
* @since 2022-07-11
*/
@Slf4j
public class WxBizMsgCrypt {
static Charset CHARSET = Charset.forName("utf-8");
Base64 base64 = new Base64();
byte[] aesKey;
String token;
String appId;
private static final int MSG_SIZE = 43;
/**
* 构造函数
* @param token 公众平台上,开发者设置的token
* @param encodingAesKey 公众平台上,开发者设置的EncodingAESKey
* @param appId 公众平台appid
**/
public WxBizMsgCrypt(String token, String encodingAesKey, String appId) throws Exception {
if (encodingAesKey.length() != MSG_SIZE) {
throw new Exception("参数错误");
}
this.token = token;
this.appId = appId;
aesKey = Base64.decodeBase64(encodingAesKey + "=");
}
/**
* 生成4个字节的网络字节序
* @param sourceNumber
* @return byte[]
*/
byte[] getNetworkBytesOrder(int sourceNumber) {
byte[] orderBytes = new byte[4];
orderBytes[3] = (byte) (sourceNumber & 0xFF);
orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
return orderBytes;
}
/**
* 还原4个字节的网络字节序
*/
int recoverNetworkBytesOrder(byte[] orderBytes) {
int sourceNumber = 0;
for (int i = 0; i < 4; i++) {
sourceNumber <<= 8;
sourceNumber |= orderBytes[i] & 0xff;
}
return sourceNumber;
}
/**
* 随机生成16位字符串
* @return String
*/
String getRandomStr() {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
SecureRandom secureRandom = new SecureRandom();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 16; i++) {
int number = secureRandom.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 对明文进行加密.
*
* @param text 需要加密的明文
* @return 加密后base64编码的字符串
*/
String encrypt(String randomStr, String text) throws Exception {
ByteGroup byteCollector = new ByteGroup();
byte[] randomStrBytes = randomStr.getBytes(CHARSET);
byte[] textBytes = text.getBytes(CHARSET);
byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
byte[] appidBytes = appId.getBytes(CHARSET);
// randomStr + networkBytesOrder + text + appid
byteCollector.addBytes(randomStrBytes);
byteCollector.addBytes(networkBytesOrder);
byteCollector.addBytes(textBytes);
byteCollector.addBytes(appidBytes);
// ... + pad: 使用自定义的填充方式对明文进行补位填充
byte[] padBytes = Pkcs7Encoder.encode(byteCollector.size());
byteCollector.addBytes(padBytes);
// 获得最终的字节流, 未加密
byte[] unencrypted = byteCollector.toBytes();
try {
// 设置加密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
// 加密
byte[] encrypted = cipher.doFinal(unencrypted);
// 使用BASE64对加密后的字符串进行编码
String base64Encrypted = base64.encodeToString(encrypted);
return base64Encrypted;
} catch (Exception e) {
e.printStackTrace();
throw new Exception();
}
}
/**
* 对密文进行解密.
*
* @param text 需要解密的密文
* @return 解密得到的明文
*/
public String decrypt(String text) throws Exception {
byte[] original;
try {
// 设置解密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
// 使用BASE64对密文进行解码
byte[] encrypted = Base64.decodeBase64(text);
// 解密
original = cipher.doFinal(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception();
}
String xmlContent, fromAppId;
try {
// 去除补位字符
byte[] bytes = Pkcs7Encoder.decode(original);
// 分离16位随机字符串,网络字节序和AppId
byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
int xmlLength = recoverNetworkBytesOrder(networkOrder);
xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
fromAppId = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
CHARSET);
} catch (Exception e) {
e.printStackTrace();
throw new Exception();
}
// appid不相同的情况
if (!fromAppId.equals(appId)) {
throw new Exception();
}
return xmlContent;
}
/**
* 将公众平台回复用户的消息加密打包.
* <ol>
* <li>对要发送的消息进行AES-CBC加密</li>
* <li>生成安全签名</li>
* <li>将消息密文和安全签名打包成xml格式</li>
* </ol>
*
* @param replyMsg 公众平台待回复用户的消息,xml格式的字符串
* @param timeStamp 时间戳,可以自己生成,也可以用URL参数的timestamp
* @param nonce 随机串,可以自己生成,也可以用URL参数的nonce
*
* @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
*/
public String encryptMsg(String replyMsg, String timeStamp, String nonce) throws Exception {
log.info("encryptMsg 加密 replyMsg:{},timeStamp:{},nonce:{}",replyMsg,timeStamp,nonce);
// 加密
String encrypt = encrypt(getRandomStr(), replyMsg);
// 生成安全签名
if (timeStamp == "") {
timeStamp = Long.toString(System.currentTimeMillis());
}
log.info("encryptMsg 生成签名getSHA1 token:{},encrypt:{}",token,encrypt);
String signature = AddSha1.getSha1(token, timeStamp, nonce, encrypt);
// 生成发送的xml
String result = XmlParse.generate(encrypt, signature, timeStamp, nonce);
log.info("encryptMsg 生成发送的xml xml:{}",result);
return result;
}
/**
* 检验消息的真实性,并且获取解密后的明文.
* <ol>
* <li>利用收到的密文生成安全签名,进行签名验证</li>
* <li>若验证通过,则提取xml中的加密消息</li>
* <li>对消息进行解密</li>
* </ol>
*
* @param msgSignature 签名串,对应URL参数的msg_signature
* @param timeStamp 时间戳,对应URL参数的timestamp
* @param nonce 随机串,对应URL参数的nonce
* @param postData 密文,对应POST请求的数据
*
* @return 解密后的原文
*/
public String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData)
throws Exception {
// 密钥,公众账号的app secret
// 提取密文
Object[] encrypt = XmlParse.extract(postData);
// 验证安全签名
String signature = AddSha1.getSha1(token, timeStamp, nonce, encrypt[1].toString());
// 和URL中的签名比较是否相等
if (!signature.equals(msgSignature)) {
throw new Exception();
}
// 解密
String result = decrypt(encrypt[1].toString());
return result;
}
}
上面这个类是微信公众号官网自己做解密弄的加解密的类,显然看着没有毛病。
以下的解决方案:
由于说是jdk安全限制问题然后升级jdk为1.9以上
-
使用 Java 9 及以上版本
- 从 Java 9 开始,默认启用了无限强度的加密,不需要手动安装 JCE,因此可以考虑升级到 Java 9 或更高版本。
-
确保密钥长度正确
- 确保你使用的密钥长度符合 AES 的要求,通常为 128、192 或 256 位。如果使用了不合法的密钥长度,也可能导致此异常。
上面的方案我升级了jdk为1.9以上,和jdk11都安装好了环境,但是项目启动都启动不了,原因是因为springboot的版本我是2.4.3,升级了jdk但是项目又又问题了换了jdk11还是不行,因为版本的依赖和项目pom的jar包冲突了,这种方案只能放弃,如果你项目纯净的可以考虑升级jdk版本。
如何你不是用的jdk8版本就可以用下面这样的方案:
如果你的 Java 版本是 8 或更早版本,你需要下载并安装 JCE Unlimited Strength Jurisdiction Policy Files。你可以从 Oracle 的官方网站下载对应你 Java 版本的 JCE 文件,并将 local_policy.jar
和 US_export_policy.jar
文件替换到你的 JDK 安装目录下的 jre/lib/security
文件夹中
那到底咋解决这个问题?
具体根本是因为某些国家的进口管制限制,JDK默认的加解密有一定的限制,也就是人家动了jdk了,你可以理解有点苹果手机的那个意思,这不是搞事情吗?
继续看:
Java Unlimited Strength Crypto Policy for Java 9 or 1.8.0_151,以下内容为该文章的翻译。
从Java 1.8.0_151和1.8.0_152开始,为JVM启用 无限制强度管辖策略 有了一种新的更简单的方法。如果不启用此功能,则不能使用AES-256。
请在 jre/lib/security
文件夹中查找文件 java.security
。
例如,对于Java 1.8.0_152
,文件结构如下所示:
/jdk1.8.0_152
|- /jre
|- /lib
|- /security
|- java.security
现在用文本编辑器打开java.security
,并找到定义java安全性属性crypto.policy
的行,它可以有两个值limited
或unlimited
- 默认值是limited
。
默认情况下,您应该能找到一条注释掉的行:
#crypto.policy=unlimited
您可以通过取消注释该行来启用无限制,删除#
:
crypto.policy=unlimited
现在重新启动指向JVM的Java应用程序即可。
我们找到这个文件,具体根据你自己的jdkl安装目录D:\software\jdk1.8.0_152\jre\lib\security
启动项目:
那是一点问题都没有了,你说你没有事动什么jdk啊?那不是妥妥的搞事情吗?