微信加密数据解密算法 Java
一。 Maven 配置
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on --> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.65</version> </dependency>
二。解密后的数据
{ "openId": "", "nickName": "", "gender": 1, "language": "", "city": "", "province": "", "country": "", "avatarUrl": "", "unionId": "", "watermark": { "timestamp": 1588254098, "appid": "" } }
多了 openId 和 unionId 两个字段。
三。相关代码
package com.x5.library.common; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.*; import java.security.spec.InvalidParameterSpecException; import java.util.Base64; public class WechatUtil { private static final Logger LOGGER = LoggerFactory.getLogger(WechatUtil.class); static { Security.addProvider(new BouncyCastleProvider()); } private static final String KEY_ALGORITHM = "AES"; private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding"; private static AlgorithmParameters generateIV(byte[] iv) throws NoSuchAlgorithmException, InvalidParameterSpecException { AlgorithmParameters parameters = AlgorithmParameters.getInstance(KEY_ALGORITHM); parameters.init(new IvParameterSpec(iv)); return parameters; } private static byte[] decrypt(byte[] content, byte[] key, byte[] iv) throws Exception { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); Key keySpec = new SecretKeySpec(key, KEY_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, keySpec, generateIV(iv)); byte[] result = cipher.doFinal(content); return result; } public static String decryptData(String encryptedData, String session_key, String ivStr) throws Exception { Base64.Decoder decoder = Base64.getDecoder(); byte[] content = decoder.decode(encryptedData); byte[] key = decoder.decode(session_key); byte[] iv = decoder.decode(ivStr); byte[] plain = decrypt(content, key, iv); String plainStr = new String(plain, StandardCharsets.UTF_8); LOGGER.debug("@@@@@@ plainStr {}", plainStr); return plainStr; } }