關鍵代碼: public String decrypt(String encryptedData, String sessionKey, String iv, String encodingFormat) throws Exception { try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); BASE64Decoder base64Decoder = new BASE64Decoder(); byte[] _encryptedData = base64Decoder.decodeBuffer(encryptedData); byte[] _sessionKey = base64Decoder.decodeBuffer(sessionKey); byte[] _iv = base64Decoder.decodeBuffer(iv); SecretKeySpec secretKeySpec = new SecretKeySpec(_sessionKey, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(_iv); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] original = cipher.doFinal(_encryptedData); byte[] bytes = WxPKCS7Encoder.decode(original); String originalString = new String(bytes, encodingFormat); return originalString; } catch (Exception ex) { return null; } } 依賴類 WxPKCS7Encoder.javaclass WxPKCS7Encoder { static Charset CHARSET = Charset.forName("utf-8"); static int BLOCK_SIZE = 32; /** * 獲得對明文進行補位填充的字節(jié). * * @param count 需要進行填充補位操作的明文字節(jié)個數 * @return 補齊用的字節(jié)數組 */ static byte[] encode(int count) { // 計算需要填充的位數 int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); if (amountToPad == 0) { amountToPad = BLOCK_SIZE; } // 獲得補位所用的字符 char padChr = chr(amountToPad); String tmp = new String(); for (int index = 0; index < amountToPad; index++) { tmp += padChr; } return tmp.getBytes(CHARSET); } /** * 刪除解密后明文的補位字符 * * @param decrypted 解密后的明文 * @return 刪除補位字符后的明文 */ static byte[] decode(byte[] decrypted) { int pad = (int) decrypted[decrypted.length - 1]; if (pad < 1 || pad > 32) { pad = 0; } return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); } /** * 將數字轉化成ASCII碼對應的字符,用于對明文進行補碼 * * @param a 需要轉化的數字 * @return 轉化得到的字符 */ static char chr(int a) { byte target = (byte) (a & 0xFF); return (char) target; } } jdk版本1.8 |