微信小程序数据解密

    public static String decrypt(String encryptedData, String ivData, String code) {
        try {
            //微信的接口,通过code获取sessionKey
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WeChatConstant.APPID_SMALL_ROUTINE +
                    "&secret=" + WeChatConstant.SECRET_SMALL_ROUTINE + "&js_code=" + code + "&grant_type=authorization_code";
            RestTemplate restTemplate = new RestTemplate();
            //进行网络请求,访问url接口
            ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
//            根据返回值进行后续操作
            String sessionKey = "";
            if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                String sessionData = responseEntity.getBody();
                //解析从微信服务器获得的openid和session_key;
                JSONObject object = JSONObject.parseObject(sessionData.trim());
                //获取用户的唯一标识  Openid
                sessionKey = object.getString("session_key");
                System.out.println(sessionKey);
            }
            byte[] encrypData1 = Base64.decodeBase64(encryptedData);
            byte[] ivData1 = Base64.decodeBase64(ivData);
            byte[] sessionKey1 = Base64.decodeBase64(sessionKey);
            int base = 16;
            if (sessionKey1.length % base != 0) {
                int groups = sessionKey1.length / base + (sessionKey1.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(sessionKey1, 0, temp, 0, sessionKey1.length);
                sessionKey1 = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(sessionKey1, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivData1));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            // 初始化
            byte[] resultByte = cipher.doFinal(encrypData1);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                System.out.println("*************************\n" + result);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 

你可能感兴趣的:(工具类,解密)