加密数据解密算法
1.对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充。
2.对称解密的目标密文为 Base64_Decode(encryptedData)。
3.对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 是16字节。
4.对称解密算法初始向量 为Base64_Decode(iv),其中iv由数据接口返回。
例子
public class WXBizDataCrypt
{
private String appId;
private String sessionKey;
public WXBizDataCrypt(String appId, String sessionKey)
{
this.appId = appId;
this.sessionKey = sessionKey;
}
public WXBizDataCrypt(){ }
public String decrypt(String encryptedData, String iv) throws Exception{
Decoder decoder = Base64.getDecoder();
byte[] keyByte = decoder.decode(sessionKey);
byte[] encryptedDataByte = decoder.decode(encryptedData);
byte[] ivByte = decoder.decode(iv);
//这边导入 bouncycastle Maven包
/*
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-ext-jdk16</artifactId>
<version>1.46</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
*/
if (Security.getProvider("BC") == null) {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
//设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, spec,parameters);
byte[] resultByte = cipher.doFinal(encryptedDataByte);
String result = null;
if (null != resultByte && resultByte.length > 0) {
result = new String(resultByte, "UTF-8");
}
// 返回前,可以对比appId
return result;
}
}
@Test
public void testBase64() {
String appId = "wx4f4bc4dec97d474b";
String sessionKey = "tiihtNczf5v6AKRyjwEUhQ==";
String encryptedData = "CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZMQmRzooG2xrDcvSnxIMXFufNstNGTyaGS9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+3hVbJSRgv+4lGOETKUQz6OYStslQ142dNCuabNPGBzlooOmB231qMM85d2/fV6ChevvXvQP8Hkue1poOFtnEtpyxVLW1zAo6/1Xx1COxFvrc2d7UL/lmHInNlxuacJXwu0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn/Hz7saL8xz+W//FRAUid1OksQaQx4CMs8LOddcQhULW4ucetDf96JcR3g0gfRK4PC7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns/8wR2SiRS7MNACwTyrGvt9ts8p12PKFdlqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYVoKlaRv85IfVunYzO0IKXsyl7JCUjCpoG20f0a04COwfneQAGGwd5oa+T8yO5hzuyDb/XcxxmK01EpqOyuxINew==";
String iv = "r7BXXKkLb8qrSNn05n0qiA==";
WXBizDataCrypt wx = new WXBizDataCrypt(appId, sessionKey);
try
{
String decrypt = wx.decrypt(encryptedData, iv);
System.out.println("answer====="+decrypt);
}
catch (Exception e)
{
e.printStackTrace();
}
}
控制台结果为
====={"openId":"oGZUI0egBJY1zhBYw2KhdUfwVJJE","nickName":"Band","gender":1,"language":"zh_CN","city":"Guangzhou","province":"Guangdong","country":"CN","avatarUrl":"http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0","unionId":"ocMvos6NjeKLIBqg5Mr9QjxrP1FA","watermark":{"timestamp":1477314187,"appid":"wx4f4bc4dec97d474b"}}
原文:https://mp.weixin.qq.com/debug/wxadoc/dev/api/signature.html