WebserviceSign.java
2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package com.bsth.util;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
public class WebserviceSign {
/**
* 生成签名
* @param map
* @return
* @throws Exception
*/
public static String getSHA1(Map<String, String> map) throws Exception {
try {
String[] array = new String[map.size()];
map.values().toArray(array);
StringBuffer sb = new StringBuffer();
// 字符串排序
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
throw e;
}
}
/**
* 生成签名
* @param map
* @return
* @throws Exception
*/
public static String getMD5(Map<String, String> map) throws Exception {
try {
String[] array = new String[map.size()];
map.values().toArray(array);
StringBuffer sb = new StringBuffer();
// 字符串排序
//Arrays.sort(array);
array = new String[] {"appoint","apple","{\"isShowCode\":\"0\",\"autoAddCart\":\"0\",\"check\":\"0\",\"skuId\":\"100012043978\",\"type\":\"1\",\"appointMoreTimeFlag\":false,\"mad\":\"0\"}","1644199231241","101"};
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
throw e;
}
}
/**
* 生成随机字符串
* @param length
* @return
*/
public static String getRandomString(int length) { //length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}