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);
   }
 }
Ejemplo n.º 3
0
  /** 如果要支持多公众账号,只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值 */
  public ApiConfig getApiConfig() {
    ApiConfig ac = new ApiConfig();

    // 配置微信 API 相关常量
    ac.setToken(PropKit.get("token"));
    ac.setAppId(PropKit.get("appId"));
    ac.setAppSecret(PropKit.get("appSecret"));

    /** 是否对消息进行加密,对应于微信平台的消息加解密方式: 1:true进行加密且必须配置 encodingAesKey 2:false采用明文模式,同时也支持混合模式 */
    ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
    ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
    return ac;
  }