pyrebot

Better not to ignore the past but learn from it instead. Otherwise, history has a way of repeating itself.

博客园 首页 新随笔 联系 订阅 管理
 1 public static String getSign(String secret, Map<String, String> params) {
 2         if (secret == null || "".equals(secret) || params == null)
 3             throw new RuntimeException("secret or params is null or blank, please check...");
 4         StringBuilder sb = new StringBuilder();//.append(secret);
 5         String result = null;
 6         try {
 7             // Set<String> sortedKeys = new TreeSet<String>();
 8             String[] keys = params.keySet().toArray(new String[0]);
 9             Arrays.sort(keys);
10             // sortedKeys.addAll(keys);
11             for (String key : keys) {
12                 String KeyValue = params.get(key);
13                 sb.append(key).append(KeyValue);
14             }
15             byte[] bytes = encryptHMAC(sb.toString(), secret);
16             //MessageDigest md = MessageDigest.getInstance("MD5");
17             result = byteTohex(bytes);
18 
19         } catch (Exception e) {
20             throw new RuntimeException(e);
21         }
22         return result;
23     }
24 
25     private static byte[] encryptHMAC(String data, String secret)throws IOException {
26         byte[] bytes = null;
27         try {
28             SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF-8"),"HmacMD5");
29             Mac mac = Mac.getInstance(secretKey.getAlgorithm());
30             mac.init(secretKey);
31             bytes = mac.doFinal(data.getBytes("UTF-8"));
32         } catch (GeneralSecurityException e) {
33             e.printStackTrace();
34         }
35         return bytes;
36     }
37 
38     public static String byteTohex(byte[] b) {
39         StringBuffer sb = new StringBuffer();
40         String stmp = "";
41 
42         for (int n = 0; n < b.length; n++) {
43             stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
44 
45             if (stmp.length() == 1)
46                 sb.append("0").append(stmp);
47             else
48                 sb.append(stmp);
49         }
50 
51         return sb.toString().toUpperCase();
52     }

 

posted on 2015-10-26 17:28  pyrebot  阅读(220)  评论(0编辑  收藏  举报