微信加密數據解密算法 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) {
		try {
			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;
		} catch (Exception e) {
			LOGGER.error(e.getLocalizedMessage());
			return e.getLocalizedMessage().getBytes();
		}
	}

	public static String decryptData(String encryptedData, String session_key, String ivStr) {
		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;
	}
}

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章