8f907b755351ad79c52e883ed8fcef54a6e316fb.svn-base 2.2 KB

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