public static String decrypt( String encryptedMsg, String timestamp, String nonce, String msgSignature) { try { ApiConfig ac = ApiConfigKit.getApiConfig(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader sr = new StringReader(encryptedMsg); InputSource is = new InputSource(sr); Document document = db.parse(is); Element root = document.getDocumentElement(); NodeList nodelist1 = root.getElementsByTagName("Encrypt"); // NodeList nodelist2 = root.getElementsByTagName("MsgSignature"); String encrypt = nodelist1.item(0).getTextContent(); // String msgSignature = nodelist2.item(0).getTextContent(); String fromXML = String.format(format, encrypt); String encodingAesKey = ac.getEncodingAesKey(); if (encodingAesKey == null) throw new IllegalStateException( "encodingAesKey can not be null, config encodingAesKey first."); WXBizMsgCrypt pc = new WXBizMsgCrypt(ac.getToken(), encodingAesKey, ac.getAppId()); return pc.decryptMsg( msgSignature, timestamp, nonce, fromXML); // 此处 timestamp 如果与加密前的不同则报签名不正确的异常 } catch (Exception e) { throw new RuntimeException(e); } }
public static String encrypt(String msg, String timestamp, String nonce) { try { ApiConfig ac = ApiConfigKit.getApiConfig(); WXBizMsgCrypt pc = new WXBizMsgCrypt(ac.getToken(), ac.getEncodingAesKey(), ac.getAppId()); return pc.encryptMsg(msg, timestamp, nonce); } catch (Exception e) { throw new RuntimeException(e); } }