sign.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import java.util.UUID;
  2. import java.util.Map;
  3. import java.util.HashMap;
  4. import java.util.Formatter;
  5. import java.security.MessageDigest;
  6. import java.security.NoSuchAlgorithmException;
  7. import java.io.UnsupportedEncodingException;
  8. class Sign {
  9. public static void main(String[] args) {
  10. String jsapi_ticket = "jsapi_ticket";
  11. // 注意 URL 一定要动态获取,不能 hardcode
  12. String url = "http://example.com";
  13. Map<String, String> ret = sign(jsapi_ticket, url);
  14. for (Map.Entry entry : ret.entrySet()) {
  15. System.out.println(entry.getKey() + ", " + entry.getValue());
  16. }
  17. };
  18. public static Map<String, String> sign(String jsapi_ticket, String url) {
  19. Map<String, String> ret = new HashMap<String, String>();
  20. String nonce_str = create_nonce_str();
  21. String timestamp = create_timestamp();
  22. String string1;
  23. String signature = "";
  24. //注意这里参数名必须全部小写,且必须有序
  25. string1 = "jsapi_ticket=" + jsapi_ticket +
  26. "&noncestr=" + nonce_str +
  27. "&timestamp=" + timestamp +
  28. "&url=" + url;
  29. System.out.println(string1);
  30. try
  31. {
  32. MessageDigest crypt = MessageDigest.getInstance("SHA-1");
  33. crypt.reset();
  34. crypt.update(string1.getBytes("UTF-8"));
  35. signature = byteToHex(crypt.digest());
  36. }
  37. catch (NoSuchAlgorithmException e)
  38. {
  39. e.printStackTrace();
  40. }
  41. catch (UnsupportedEncodingException e)
  42. {
  43. e.printStackTrace();
  44. }
  45. ret.put("url", url);
  46. ret.put("jsapi_ticket", jsapi_ticket);
  47. ret.put("nonceStr", nonce_str);
  48. ret.put("timestamp", timestamp);
  49. ret.put("signature", signature);
  50. return ret;
  51. }
  52. private static String byteToHex(final byte[] hash) {
  53. Formatter formatter = new Formatter();
  54. for (byte b : hash)
  55. {
  56. formatter.format("%02x", b);
  57. }
  58. String result = formatter.toString();
  59. formatter.close();
  60. return result;
  61. }
  62. private static String create_nonce_str() {
  63. return UUID.randomUUID().toString();
  64. }
  65. private static String create_timestamp() {
  66. return Long.toString(System.currentTimeMillis() / 1000);
  67. }
  68. }