微信退款回撥資訊解密筆記
阿新 • • 發佈:2019-01-01
微信退款回撥資訊解密過程記錄,方便自己檢視
解密步驟:
(1)對加密串A做base64解碼,得到加密串B
(2)對商戶key做md5,得到32位小寫key* ( key設定路徑:微信商戶平臺(pay.weixin.qq.com)-->賬戶設定-->API安全-->金鑰設定 )
(3)用key*對加密串B做AES-256-ECB解密(PKCS7Padding)
import java.util.Base64; public class Base64Util { /** * 解碼 * @param encodedText * @return */ public static byte[] decode(String encodedText){ final Base64.Decoder decoder = Base64.getDecoder(); return decoder.decode(encodedText); } /** * 編碼 * @param data * @return */ public static String encode(byte[] data){ final Base64.Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(data); } }
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class AESUtil { /** * 金鑰演算法 */ private static final String ALGORITHM = "AES"; /** * 加解密演算法/工作模式/填充方式 */ private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding"; /** * AES加密 * * @param data * @return * @throws Exception */ public static String encryptData(String data,String password) throws Exception { // 建立密碼器 Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING); SecretKeySpec key = new SecretKeySpec(MD5.MD5Encode(password).toLowerCase().getBytes(), ALGORITHM); // 初始化 cipher.init(Cipher.ENCRYPT_MODE, key); return Base64Util.encode(cipher.doFinal(data.getBytes())); } /** * AES解密 * * @param base64Data * @return * @throws Exception */ public static String decryptData(String base64Data,String password) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING); SecretKeySpec key = new SecretKeySpec(MD5.MD5Encode(password).toLowerCase().getBytes(), ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decode = Base64Util.decode(base64Data); byte[] doFinal = cipher.doFinal(decode); return new String(doFinal,"utf-8"); } }
/** * InputStream流轉換成String字串 * @param inStream InputStream流 * @param encoding 編碼格式 * @return String字串 */ public static String inputStreamToString(InputStream inStream, String encoding){ String result = null; try { if(inStream != null){ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] tempBytes = new byte[1024]; int count = -1; while((count = inStream.read(tempBytes, 0, 1024)) != -1){ outStream.write(tempBytes, 0, count); } tempBytes = null; outStream.flush(); result = new String(outStream.toByteArray(), encoding); } } catch (Exception e) { result = null; } return result; } /** * xml轉換成map * @param xml * @return */ public static Map<String, String> readStringXmlOut(String xml) { Map<String, String> map = new HashMap<String, String>(); Document doc = null; try { doc = DocumentHelper.parseText(xml); // 將字串轉為XML Element rootElt = doc.getRootElement(); // 獲取根節點 List<Element> list = rootElt.elements();// 獲取根節點下所有節點 for (Element element : list) { // 遍歷節點 map.put(element.getName(), element.getText()); // 節點的name為map的key,text為map的value } } catch (DocumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return map; }
測試方法
列印結果: