Java解密微信小程序數據,獲得手機號碼

微信官方文檔地址

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

/**
	 * Description: 解密微信數據,獲得手機號碼
	 * 
	 * @param data
	 * @param sessionid
	 * @return
	 * @throws Exception
	 */
	public String decrypt(String data, String sessionid) throws Exception {
        // 傳入參數JSON格式校驗與轉換
		Map<String, Object> dataMap = JSONDataUtil.checkJSONData(data);
		Map<String, Object> resultMap = new HashMap<>();

		try {
            // 檢查map裏字符串不能爲空
			String iv = MapUtil.checkStringExistMap(dataMap, "iv");// 偏移量
			String sessionKey = MapUtil.checkStringExistMap(dataMap, "session_key");// 密鑰
			String encryptedData = MapUtil.checkStringExistMap(dataMap, "encryptedData");// 密文

			// 解密
			String deInfo = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
			if (deInfo == null) {
				throw new Exception(-1, "用戶信息解密失敗");
			}
			Map<String, Object> infoMap = JSONDataUtil.checkJSONData(deInfo);
			
			if (StringUtils.isEmpty(infoMap.get("phoneNumber"))) {
				throw new Exception(-1, "無法獲得用戶手機號");
			}

			resultMap.put("phone", infoMap.get("phoneNumber"));
			return new RetStruct("解密成功", resultMap).toString();
		} catch (Exception e) {
			throw new Exception(e);
		}
	}
import java.security.AlgorithmParameters;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class AesCbcUtil {
	static {
		// BouncyCastle是一個開源的加解密解決方案,主頁在http://www.bouncycastle.org/
		Security.addProvider(new BouncyCastleProvider());
	}

	/**
	 * AES解密
	 *
	 * @param data
	 *            //密文,被加密的數據
	 * @param key
	 *            //祕鑰
	 * @param iv
	 *            //偏移量
	 * @param encodingFormat
	 *            //解密後的結果需要進行的編碼
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
		// 被加密的數據
		byte[] dataByte = Base64.decodeBase64(data);
		// 加密祕鑰
		byte[] keyByte = Base64.decodeBase64(key);
		// 偏移量
		byte[] ivByte = Base64.decodeBase64(iv);
		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
			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(dataByte);
			if (null != resultByte && resultByte.length > 0) {
				String result = new String(resultByte, encodingFormat);
				return result;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} 
	}
}

 

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