b0b9a2a8e84d568b2d37ed63764c753e86c32bd1.svn-base 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * 对公众平台发送给公众账号的消息加解密示例代码.
  3. *
  4. * @copyright Copyright (c) 1998-2014 Tencent Inc.
  5. */
  6. // ------------------------------------------------------------------------
  7. package com.yihu.utils.aes;
  8. import java.io.StringReader;
  9. import javax.xml.parsers.DocumentBuilder;
  10. import javax.xml.parsers.DocumentBuilderFactory;
  11. import org.w3c.dom.Document;
  12. import org.w3c.dom.Element;
  13. import org.w3c.dom.NodeList;
  14. import org.xml.sax.InputSource;
  15. /**
  16. * XMLParse class
  17. *
  18. * 提供提取消息格式中的密文及生成回复消息格式的接口.
  19. */
  20. class XMLParse {
  21. /**
  22. * 提取出xml数据包中的加密消息
  23. * @param xmltext 待提取的xml字符串
  24. * @return 提取出的加密消息字符串
  25. * @throws AesException
  26. */
  27. public static Object[] extract(String xmltext) throws AesException {
  28. Object[] result = new Object[3];
  29. try {
  30. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  31. DocumentBuilder db = dbf.newDocumentBuilder();
  32. StringReader sr = new StringReader(xmltext);
  33. InputSource is = new InputSource(sr);
  34. Document document = db.parse(is);
  35. Element root = document.getDocumentElement();
  36. NodeList nodelist1 = root.getElementsByTagName("Encrypt");
  37. NodeList nodelist2 = root.getElementsByTagName("ToUserName");
  38. result[0] = 0;
  39. result[1] = nodelist1.item(0).getTextContent();
  40. result[2] = nodelist2.item(0).getTextContent();
  41. return result;
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. throw new AesException(AesException.ParseXmlError);
  45. }
  46. }
  47. /**
  48. * 生成xml消息
  49. * @param encrypt 加密后的消息密文
  50. * @param signature 安全签名
  51. * @param timestamp 时间戳
  52. * @param nonce 随机字符串
  53. * @return 生成的xml字符串
  54. */
  55. public static String generate(String encrypt, String signature, String timestamp) {
  56. String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
  57. + "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
  58. + "<TimeStamp>%3$s</TimeStamp>\n" + "</xml>";
  59. return String.format(format, encrypt, signature, timestamp);
  60. }
  61. }