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 dataMap = JSONDataUtil.checkJSONData(data);
		Map 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 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;
		} 
	}
}

 

你可能感兴趣的:(工具)