關(guān)鍵代碼: 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; /** * 獲得對(duì)明文進(jìn)行補(bǔ)位填充的字節(jié). * * @param count 需要進(jìn)行填充補(bǔ)位操作的明文字節(jié)個(gè)數(shù) * @return 補(bǔ)齊用的字節(jié)數(shù)組 */ static byte[] encode(int count) { // 計(jì)算需要填充的位數(shù) int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); if (amountToPad == 0) { amountToPad = BLOCK_SIZE; } // 獲得補(bǔ)位所用的字符 char padChr = chr(amountToPad); String tmp = new String(); for (int index = 0; index < amountToPad; index++) { tmp += padChr; } return tmp.getBytes(CHARSET); } /** * 刪除解密后明文的補(bǔ)位字符 * * @param decrypted 解密后的明文 * @return 刪除補(bǔ)位字符后的明文 */ 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); } /** * 將數(shù)字轉(zhuǎn)化成ASCII碼對(duì)應(yīng)的字符,用于對(duì)明文進(jìn)行補(bǔ)碼 * * @param a 需要轉(zhuǎn)化的數(shù)字 * @return 轉(zhuǎn)化得到的字符 */ static char chr(int a) { byte target = (byte) (a & 0xFF); return (char) target; } } jdk版本1.8 |
工作日 8:30-12:00 14:30-18:00
周六及部分節(jié)假日提供值班服務(wù)