微信小程序加密介绍
我们开发微信小程序的过程中,我们的服务端有时需要获取微信提供的开放数据。微信会对这些开放数据做签名和加密处理。开发者后台拿到开放数据后可以对数据进行校验签名和解密,来保证数据不被篡改。
官方详细介绍:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html#method-decode
微信官方提供了多种编程语言的示例代码,但是目前下载的示例代码只有C++,Node,PHP,以及Python语言的,没有Java语言的,所以需要我们自己实现解密算法。
Bouncy Castle Crypto工具包解密
Bouncy Castle Crypto包是一个加密算法的Java实现。这个jar包含了用于JDK1.5及以上的JCE提供程序和Bouncy Castle加密的轻量级API。
引入依赖
Bouncy Castle Crypto包有许多版本的jar包,可以在Maven仓库(https://mvnrepository.com/)搜索bcprov-jdk
,选择适合自己的版本jar,我这使用的是受欢迎比较多的bcprov-jdk15on
,它适用于JDK1.5及以上版本。
gradle文件:
implementation "org.bouncycastle:bcprov-jdk15on:1.69"
maven文件:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.69</version>
</dependency>
算法实现
public static String decryptWxData(String encryptedData, String sessionKey, String iv) {
try {
// 初始化
Security.addProvider(new BouncyCastleProvider());
SecretKeySpec spec = new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(Base64.decodeBase64(iv)));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
byte[] resultByte = cipher.doFinal(Base64.decodeBase64(encryptedData));
if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, StandardCharsets.UTF_8);
log.info(">>>>> 微信加密数据解析结果:{}", result);
return result;
}
} catch (Exception e) {
log.error(">>>>> 微信加密数据解析失败:", e);
}
return null;
}
Hutool工具类解密
Hutool是一个小而全的Java工具类库,封装了很多实用的静态方法,我们可以使用这个依赖包的相关工具类来简单封装,从而实现微信小程序加密数据的解密。
引入依赖
gradle文件:
implementation 'cn.hutool:hutool-all:5.7.16'
maven文件:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.16</version>
</dependency>
算法实现
我们只需要两行代码即可实现数据解密,但是解密后的字节数组末尾可能带有补位字符,所以我们需要判断是否有补位字符,如果有则删除这些字符。
public static String decryptWxDataOfHutool(String encryptedData, String sessionKey, String iv) {
AES aes = new AES(Mode.CBC, Padding.NoPadding, Base64.decodeBase64(sessionKey),
Base64.decodeBase64(iv));
byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData));
if (null != resultByte && resultByte.length > 0) {
// 删除解密后明文的补位字符
int padNum = resultByte[resultByte.length - 1];
if (padNum < 1 || padNum > 32) {
padNum = 0;
}
resultByte = Arrays.copyOfRange(resultByte, 0, resultByte.length - padNum);
String result = new String(resultByte, StandardCharsets.UTF_8);
log.info(">>>>> 微信加密数据解析结果:{}", result);
return result;
}
return null;
}
验证
这套加密算法是适用于微信小程序的绝大部分加密数据的,所以我们使用带有用户手机号的加密串,进行解密验证。
注意,验证测试的时候,需要将以下三个变量的值替换为自己小程序的,不然会报错。
public static void main(String[] args) {
String encryptedData = "je8FUw5ivIMnbW/SUeJzEqb1dqiv8S1c1oJ+aVcktjnkdMcq16TLBbkiDug1Km2sxuu5nmO5j9QGLWREOAkaHwjJH/2lHliq8D3MSl9q9fE5WtNtwO0BsBh/DBhLVaRFwpwEWGhspRy9TL+PO8lezkb3E0xdZVdQKB0SbAqhDUe8k5j7fG4G6oxvvrg7DnxV8uKi67Mo1RGFAx1QjtffFw==";
String sessionKey = "Eq5Bao4+Niiyqv\\/GmEFR4A==";
String iv = "zr75JDqgcc23AKQxmzZykA==";
decryptWxDataOfHutool(encryptedData, sessionKey, iv);
decryptWxData(encryptedData, sessionKey, iv);
}
成功运行后,可以得到如下正确的数据:
{
"phoneNumber":"18825412340",
"purePhoneNumber":"18825412340",
"countryCode":"86",
"watermark":{
"timestamp":1637287930,
"appid":"wx17e20c3acb11ef2a"
}
}
完整代码
package com.chenpi;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
@Slf4j
public class WxUtils {
public static String decryptWxData(String encryptedData, String sessionKey, String iv) {
try {
// 初始化
Security.addProvider(new BouncyCastleProvider());
SecretKeySpec spec = new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(Base64.decodeBase64(iv)));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
byte[] resultByte = cipher.doFinal(Base64.decodeBase64(encryptedData));
if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, StandardCharsets.UTF_8);
log.info(">>>>> 微信加密数据解析结果:{}", result);
return result;
}
} catch (Exception e) {
log.error(">>>>> 微信加密数据解析失败:", e);
}
return null;
}
public static String decryptWxDataOfHutool(String encryptedData, String sessionKey, String iv) {
AES aes = new AES(Mode.CBC, Padding.NoPadding, Base64.decodeBase64(sessionKey),
Base64.decodeBase64(iv));
byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData));
if (null != resultByte && resultByte.length > 0) {
// 删除解密后明文的补位字符
int padNum = resultByte[resultByte.length - 1];
if (padNum < 1 || padNum > 32) {
padNum = 0;
}
resultByte = Arrays.copyOfRange(resultByte, 0, resultByte.length - padNum);
String result = new String(resultByte, StandardCharsets.UTF_8);
log.info(">>>>> 微信加密数据解析结果:{}", result);
return result;
}
return null;
}
public static void main(String[] args) {
String encryptedData = "9d9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Od1A81p87JOmX3bCp3tgU8k5w+de3Ual4hdDcHK8AJUfrT8H5BDtY5LP2Ny/rD3X6VuO9//WQpszEFprosDZcb0SBTG3dxeIr4lb1I9MHVtJoEOfwLV8WtUN6Rdn/kGZ1nInSAuMyqZLBRfAX2603lv91SkghnY+FT3PCuqaDPDEDUgd/ozM9DWfaI9eaC/OC5NU+WqW9s17Q3+cLaWF7VZswloRuS/8LMrahxmTcDnIFRV+S1SeyV+Bdm79qseeQEdsSVDdLO2aJ1iViLxzbebb8pUIhx10JMacUrOBFVB+J76lLR4AiVT8rydLRA6uq5fFCMlg2GDXVBkbgqUoBVuiozGLKjPPSmfbk5s9JMxa8zSTZ6Vq4EefAeWoSKiWKHtBkFWcUEbp6I2+YycS3kqP8kC069csssGcHqDA6ouP+wEkpoDVS3vFi4fVkpjBtpY5Fu+NIQYUfiC54EA2JMyBS3lHGv01oPW54o4uSZoglcb2S6Yf9fkgS48ft0xE7Yi0YTQBct2jVTOSq5jjwxb26pjAhfkkccdvjZD3wHZSl/dNEsOWdKrdhE6H93Rvqny/nvQFX0DDzZPs1O2rbRAGxgHtKSDfxjWC6g==";
String sessionKey = "VrgQ9xkONam93c+ULD0yLA==";
String iv = "W4ND0KBskxNNnSRCuapaqQ==";
decryptWxDataOfHutool(encryptedData, sessionKey, iv);
decryptWxData(encryptedData, sessionKey, iv);
}
}
本次分享到此结束啦~~
到此这篇关于Java实现微信小程序加密数据解密算法的文章就介绍到这了,更多相关微信小程序加密数据解密算法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!