需要添加的依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
配置信息
/**
* wx 配置文件
* */
public class WxConstant {
//appid
public static final String appid = "";
//appsecret
public static final String secret = "";
public static final String authApi = "https://api.weixin.qq.com/sns/jscode2session";
public static final String AES = "AES";
public static final String AES_CBC_PADDING = "AES/CBC/PKCS7Padding";
}
import cn.hutool.http.HttpUtil;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;
public class WxUtils {
public static String wxDecrypt(String encrypted, String session_key, String iv) {
String result = null;
byte[] encrypted64 = Base64.decodeBase64(encrypted);
byte[] key64 = Base64.decodeBase64(session_key);
byte[] iv64 = Base64.decodeBase64(iv);
try {
init();
result = new String(decrypt(encrypted64, key64, generateIV(iv64)));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* * 初始化密钥
*
*/
public static void init() throws Exception {
Security.addProvider(new BouncyCastleProvider());
KeyGenerator.getInstance(WxConstant.AES).init(128);
}
/**
* * 生成iv
*
*/
public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
// iv 为一个 16 字节的数组,这里采用和 iOS 端一样的构造方法,数据全为0
// Arrays.fill(iv, (byte) 0x00);
AlgorithmParameters params = AlgorithmParameters.getInstance(WxConstant.AES);
params.init(new IvParameterSpec(iv));
return params;
}
/**
* * 生成解密
*
*/
public static byte[] decrypt(byte[] encryptedData, byte[] keyBytes, AlgorithmParameters iv)
throws Exception {
Key key = new SecretKeySpec(keyBytes, WxConstant.AES);
Cipher cipher = Cipher.getInstance(WxConstant.AES_CBC_PADDING);
// 设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(encryptedData);
}
/**
* 根据code获取
* @param code
* @return
*/
public static String getLoginInfo(String code){
String url = WxConstant.authApi+"?" +
"appid="+WxConstant.appid +
"&secret="+WxConstant.secret+
"&js_code="+code+
"&grant_type=authorization_code";
String result = HttpUtil.createGet(url)
.execute()
.charset("utf-8")
.body();
return result;
}
}