위챗 애플릿 데이터 복호화

    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("*************************
" + result); return result; } } catch (Exception e) { e.printStackTrace(); } return null; }

좋은 웹페이지 즐겨찾기