pom 依赖
非必须,hutool 是为了使用 AES 工具类,bcprov 是为了使用 PKCS7Padding,都可以自己实现,这里为了方便。
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>${hutool-all.version}</version> </dependency> <dependency><!--AES/CBC/PKCS7Padding--> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15to18</artifactId> <version>${bcprov-jdk15to18.version}</version> </dependency>
工具类
import cn.hutool.core.codec.Base64; import cn.hutool.crypto.symmetric.AES; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import java.nio.charset.StandardCharsets; public class WeChatUtil { private static final String WATERMARK = "watermark"; private static final String APPID = "appid"; public static String decrypt(String appId, String sessionKey, String encryptedData, String iv) { String result = ""; try { AES aes = new AES("CBC", "PKCS7Padding", Base64.decode(sessionKey), Base64.decode(iv)); byte[] resultByte = aes.decrypt(Base64.decode(encryptedData)); if (null != resultByte && resultByte.length > 0) { result = new String(resultByte, StandardCharsets.UTF_8); JSONObject jsonObject = JSONUtil.parseObj(result); String decryptAppid = jsonObject.getJSONObject(WATERMARK).getStr(APPID); if (!appId.equals(decryptAppid)) { result = ""; } } } catch (Exception e) { result = ""; e.printStackTrace(); } return result; } }
测试
public static void main(String[] args) { String appId = "wx4f4bc4dec97d474b"; String encryptedData = "CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZMQmRzooG2xrDcvSnxIMXFufNstNGTyaGS9uT5geRa0W4oTOb1WT7fJl" + "AC+oNPdbB+3hVbJSRgv+4lGOETKUQz6OYStslQ142dNCuabNPGBzlooOmB231qMM85d2/fV6ChevvXvQP8Hkue1poOFtnEtpyxVLW" + "1zAo6/1Xx1COxFvrc2d7UL/lmHInNlxuacJXwu0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn/Hz7saL8xz+W//FRAUid1OksQaQx4CMs" + "8LOddcQhULW4ucetDf96JcR3g0gfRK4PC7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns/8wR2" + "SiRS7MNACwTyrGvt9ts8p12PKFdlqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYVoKlaRv85IfVunYzO0IKXsyl7JCUjCpoG20f0a04COw" + "fneQAGGwd5oa+T8yO5hzuyDb/XcxxmK01EpqOyuxINew=="; String sessionKey = "tiihtNczf5v6AKRyjwEUhQ=="; String iv = "r7BXXKkLb8qrSNn05n0qiA=="; System.out.println(WeChatUtil.decrypt(appId, sessionKey, encryptedData, iv)); }
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html#加密数据解密算法