All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.qq.weixin.mp.aes.XMLParse Maven / Gradle / Ivy

Go to download

The weixin-popular is a JAVA SDK for weixin. Weixin web url is https://mp.weixin.qq.com.

The newest version!
/**
 * 对公众平台发送给公众账号的消息加解密示例代码.
 * 
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

// ------------------------------------------------------------------------

package com.qq.weixin.mp.aes;

import java.io.StringReader;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * XMLParse class
 *
 * 提供提取消息格式中的密文及生成回复消息格式的接口.
 */
class XMLParse {

	/**
	 * 提取出xml数据包中的加密消息
	 * @param xmltext 待提取的xml字符串
	 * @return 提取出的加密消息字符串
	 * @throws AesException 
	 */
	public static Object[] extract(String xmltext) throws AesException     {
		Object[] result = new Object[3];
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			
			/*
			 * 避免 XXE 攻击
			 * @since 2.8.21 
			 */
			dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
			dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
	        dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
	        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
	        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
	        dbf.setXIncludeAware(false);
	        dbf.setExpandEntityReferences(false);
			
			DocumentBuilder db = dbf.newDocumentBuilder();
			StringReader sr = new StringReader(xmltext);
			InputSource is = new InputSource(sr);
			Document document = db.parse(is);

			Element root = document.getDocumentElement();
			NodeList nodelist1 = root.getElementsByTagName("Encrypt");
			NodeList nodelist2 = root.getElementsByTagName("ToUserName");
			//公众平台使用ToUserName,第三方平台使用 AppId
			if(nodelist2 == null || nodelist2.item(0) == null){
				nodelist2 = root.getElementsByTagName("AppId");
			}
			result[0] = 0;
			result[1] = nodelist1.item(0).getTextContent();
			result[2] = nodelist2.item(0).getTextContent();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new AesException(AesException.ParseXmlError);
		}
	}

	/**
	 * 生成xml消息
	 * @param encrypt 加密后的消息密文
	 * @param signature 安全签名
	 * @param timestamp 时间戳
	 * @param nonce 随机字符串
	 * @return 生成的xml字符串
	 */
	public static String generate(String encrypt, String signature, String timestamp, String nonce) {

		String format = "\n" + "\n"
				+ "\n"
				+ "%3$s\n" + "\n" + "";
		return String.format(format, encrypt, signature, timestamp, nonce);

	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy