8f34e25a3fbaa8e502890eb67f5c81d488c4b6f2.svn-base 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.yihu.utils;
  2. import java.io.UnsupportedEncodingException;
  3. import java.security.MessageDigest;
  4. import java.security.NoSuchAlgorithmException;
  5. import java.util.Formatter;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import java.util.UUID;
  9. import net.sf.json.JSONObject;
  10. public class WxConfig
  11. {
  12. private static String byteToHex(final byte[] hash) {
  13. Formatter formatter = new Formatter();
  14. for (byte b : hash)
  15. {
  16. formatter.format("%02x", b);
  17. }
  18. String result = formatter.toString();
  19. formatter.close();
  20. return result;
  21. }
  22. private static String create_nonce_str() {
  23. return UUID.randomUUID().toString().trim().replaceAll("-", "");
  24. }
  25. private static String create_timestamp() {
  26. return Long.toString(System.currentTimeMillis() / 1000);
  27. }
  28. public static JSONObject getConfig(String jsapi_ticket, String url) {
  29. JSONObject ret = new JSONObject();
  30. String nonce_str = create_nonce_str();
  31. String timestamp = create_timestamp();
  32. String string1;
  33. String signature = "";
  34. string1 = "jsapi_ticket=" + jsapi_ticket +
  35. "&noncestr=" + nonce_str +
  36. "&timestamp=" + timestamp +
  37. "&url=" + url;
  38. try
  39. {
  40. MessageDigest crypt = MessageDigest.getInstance("SHA-1");
  41. crypt.reset();
  42. crypt.update(string1.getBytes("UTF-8"));
  43. signature = byteToHex(crypt.digest());
  44. }
  45. catch (NoSuchAlgorithmException e)
  46. {
  47. e.printStackTrace();
  48. }
  49. catch (UnsupportedEncodingException e)
  50. {
  51. e.printStackTrace();
  52. }
  53. ret.put("url", url);
  54. ret.put("jsapi_ticket", jsapi_ticket);
  55. ret.put("nonceStr", nonce_str);
  56. ret.put("timestamp", timestamp);
  57. ret.put("signature", signature);
  58. return ret;
  59. }
  60. public static void main(String[] args) {
  61. String jsapi_ticket = "jsapi_ticket";
  62. String url = "http://example.com";
  63. Map<String, String> ret = getConfig(jsapi_ticket, url);
  64. for (Map.Entry entry : ret.entrySet()) {
  65. System.out.println(entry.getKey() + ":" + entry.getValue());
  66. }
  67. }
  68. }