View Javadoc
1   package com.foxinmy.weixin4j.wxa;
2   
3   import java.nio.charset.Charset;
4   
5   import org.apache.commons.codec.binary.Base64;
6   
7   import com.alibaba.fastjson.JSON;
8   import com.alibaba.fastjson.JSONObject;
9   
10  /**
11   * 对微信小程序用户加密数据的解密。
12   *
13   * @since 1.8
14   * @see <a href="https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html">开放数据校验与解密</a>
15   */
16  public class WXBizDataCrypt {
17  
18  	private final String appId;
19  
20  	private final String sessionKey;
21  
22  	public WXBizDataCrypt(String appId, String sessionKey) {
23  		this.appId = appId;
24  		this.sessionKey = sessionKey;
25  	}
26  
27  	/**
28  	 * 解密微信小程序用户加密数据.
29  	 *
30  	 * @param encryptedData 加密的用户数据.
31  	 * @param iv 与用户数据一同返回的初始向量.
32  	 * @return 解密后的原文.
33  	 */
34  	public JSONObject decryptData(final String encryptedData, final String iv) {
35  		final byte[] aesKey = Base64.decodeBase64(sessionKey);
36  		final byte[] aesCipher = Base64.decodeBase64(encryptedData);
37  		final byte[] aesIV = Base64.decodeBase64(iv);
38  
39  		final byte[] decryptedBytes = AESUtils.decrypt(aesCipher, aesKey, aesIV);
40  		final String decryptedText = new String(decryptedBytes, Charset.forName("UTF-8"));
41  		final JSONObject decrypted = JSON.parseObject(decryptedText);
42  
43  		final String watermarkAppId = decrypted.getJSONObject("watermark").getString("appid");
44  		if (!watermarkAppId.equals(this.appId)) {
45  			throw new IllegalArgumentException("Invalid Buffer");
46  		}
47  
48  		return decrypted;
49  	}
50  
51  }