最近朋友在弄微信小程序开发,需要跟微信服务端交互,微信敏感数据都有加密返回,需要在服务端接收进行解密后再返回给客户端小程序,今天就通过Java进行数据的解密,以下展示是Java代码
如果你使用的C#,请访问这个地址(C#版本) https://blog.csdn.net/jasonsong2008/article/details/83586119
我们先来看一下微信官方的说明文档,以下直接文档来自微信小程序官方:
加密数据解密算法
接口如果涉及敏感数据(如wx.getUserInfo
当中的 openId 和 unionId),接口的明文内容将不包含这些敏感数据。开发者如需要获取敏感数据,需要对接口返回的加密数据(encryptedData) 进行对称解密。 解密算法如下:
- 对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充。
- 对称解密的目标密文为 Base64_Decode(encryptedData)。
- 对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 是16字节。
- 对称解密算法初始向量 为Base64_Decode(iv),其中iv由数据接口返回。
通过微信文档的说明编写了如下解密方法供大家使用
import org.apache.shiro.codec.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* AES解密(JAVA版本)
* Add by 成长的小猪(Jason.Song) on 2018/10/26
* http://blog.csdn.net/jasonsong2008
*/
public class AesHelper {
/**
* 微信小程序 开放数据解密
* AES解密(Base64)
* Add by 成长的小猪(Jason.Song) on 2018/10/26
* @param encryptedData 已加密的数据
* @param sessionKey 解密密钥
* @param iv IV偏移量
* @return
* @throws Exception
*/
public static String decryptForWeChatApplet(String encryptedData, String sessionKey, String iv) throws Exception {
byte[] decryptBytes = Base64.decode(encryptedData);
byte[] keyBytes = Base64.decode(sessionKey);
byte[] ivBytes = Base64.decode(iv);
return new String(decryptByAesBytes(decryptBytes, keyBytes, ivBytes));
}
/**
* AES解密
* Add by 成长的小猪(Jason.Song) on 2018/10/26
* @param decryptedBytes 待解密的字节数组
* @param keyBytes 解密密钥字节数组
* @param ivBytes IV初始化向量字节数组
* @return
* @throws Exception
*/
public static byte[] decryptByAesBytes(byte[] decryptedBytes, byte[] keyBytes, byte[] ivBytes) throws Exception {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec iv = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] outputBytes = cipher.doFinal(decryptedBytes);;
return outputBytes;
}
}
下面是通过以上解密方法进行测试,大家根据自己的情况进行相应调用即可
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
/**
* 文章来源于成长的小猪
* http://blog.csdn.net/jasonsong2008
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/applicationContext.xml"})
public class AesHelperTest {
@Test
public void decryptForWeChatApplet() {
//微信小程序返回的加密数据
String encryptedData =
"tsyLVebikY1aLQ0aNpg10NHxCTV2Ar+FJHUZdwIchBXFbJU7hXyf5gbDibaLU+lT6bzzut/nVymRFp/U8MrF0c8yOCFbnK5aevyearR7vopeel2y929weVA/s16shDPnRMkIn9xiMfVY3LDmuptnBpy1loZfSW2CPfXFuKXQf2z+Kiruynve1cq2mnzAadNaw3/g/tjHRPzxBnTkMsu8sQ==";
//会话密钥
String sessionKey = "vBwBswWRVmD0WQvRbdbMZg==";
//解密算法初始向量
String iv = "8IzE0WUF0j5hXy4oIKuLHA==";
try {
String result = AesHelper.decryptForWeChatApplet(encryptedData, sessionKey, iv);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}