微信加密数据解密算法 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;
	}
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值