常用工具类

均来自互联网,自己有些微改动,持续更新中

MD5加密

Maven 依赖–spring boot

1
2
3
4
5
6
7
8
9
<!--md5加密依赖-->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
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
public class MD5Util {

/**
* 盐
*/
private static final String SALT = "1a2b3c4d";

private static String md5(String src){
return DigestUtils.md5Hex(src);
}

/**
* 第一次加密
* @param inputPass 前端输入的密码
* @return 加密后的密码
*/
public static String inputPassToFormPass(String inputPass){
//md5加密密码前,先对密码进行处理,按以下salt的规则处理密码
String str = "" + SALT.charAt(0) + SALT.charAt(3) +
inputPass + SALT.charAt(2) + SALT.charAt(5);
return md5(str);
}

/**
* 第二次加密
* @param formPass 第一次加密后的结果
* @param salt 盐
* @return 加密后的存入数据库的密码
*/
public static String formPassToDBPass(String formPass, String salt){
String str = "" + salt.charAt(1) + salt.charAt(5) + formPass + salt.charAt(3) + salt.charAt(6);
return md5(str);
}

/**
* 实际调用的方法,直接包含两次加密
* @param inputPass 前端输入密码
* @param salt 盐
* @return 加密后的存入数据库的密码
*/
public static String inputPassToDBPass(String inputPass, String salt){
//第一次加密
String formPass = inputPassToFormPass(inputPass);
//第二次加密
return formPassToDBPass(formPass, salt);
}

/**
* 测试一下
* @param args
*/
public static void main(String[] args) {
//b6f500ed7576bf832f970eb71479667c
System.out.println(inputPassToFormPass("123456"));
System.out.println(formPassToDBPass("b6f500ed7576bf832f970eb71479667c", "asdfg1243"));
System.out.println(inputPassToDBPass("123456", "asdfg1243"));
}
}

Cookies工具类

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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
public class CookieUtil {
/**
* 得到Cookie的值, 不编码
*
* @param request
* @param cookieName 名称
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName) {
return getCookieValue(request, cookieName, false);
}

/**
* 得到Cookie的值,根据isDecode判断是否解码
* 默认解码格式为utf-8
*
* @param request
* @param cookieName 名称
* @param isDecoder 是否解码
* @return
*/
public static String getCookieValue(HttpServletRequest request,
String cookieName,
boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
//遍历cookies开始查找
for (Cookie cookie : cookieList) {
if (cookie.getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookie.getValue(),
"UTF-8");
} else {
retValue = cookie.getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}

/**
* 得到Cookie的值,可指定解码格式
*
* @param request
* @param cookieName 名称
* @param encodeString 解码格式
* @return
*/
public static String getCookieValue(HttpServletRequest request,
String cookieName,
String encodeString) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (Cookie cookie : cookieList) {
if (cookie.getName().equals(cookieName)) {
retValue = URLDecoder.decode(cookie.getValue(),
encodeString);
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}

/**
* 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
*
* @param request
* @param response
* @param cookieName 名称
* @param cookieValue 需要设置的值
*/
public static void setCookie(HttpServletRequest request,
HttpServletResponse response,
String cookieName,
String cookieValue) {
setCookie(request, response, cookieName, cookieValue, -1);
}

/**
* 设置Cookie的值 在指定时间内生效,但不编码
*
* @param request
* @param response
* @param cookieName 名称
* @param cookieValue 需要设置的值
* @param cookieMaxage 生效时间
*/
public static void setCookie(HttpServletRequest request,
HttpServletResponse response,
String cookieName,
String cookieValue,
int cookieMaxage) {
setCookie(request, response, cookieName, cookieValue, cookieMaxage,
false);
}

/**
* 设置Cookie的值 不设置生效时间,可以选择是否编码
*
* @param request
* @param response
* @param cookieName 名称
* @param cookieValue 设置值
* @param isEncode 是否编码
*/
public static void setCookie(HttpServletRequest request,
HttpServletResponse response,
String cookieName,
String cookieValue,
boolean isEncode) {
setCookie(request, response, cookieName, cookieValue, -1, isEncode);
}

/**
* 设置Cookie的值 在指定时间内生效, 编码参数
*
* @param request
* @param response
* @param cookieName 名称
* @param cookieValue 设置值
* @param cookieMaxage 生效时间
* @param isEncode 是否编码
*/
public static void setCookie(HttpServletRequest request,
HttpServletResponse response,
String cookieName,
String cookieValue,
int cookieMaxage,
boolean isEncode) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
}

/**
* 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
*
* @param request
* @param response
* @param cookieName 名称
* @param cookieValue 设置值
* @param cookieMaxage 生效时间
* @param encodeString 编码格式
*/
public static void setCookie(HttpServletRequest request,
HttpServletResponse response,
String cookieName,
String cookieValue,
int cookieMaxage,
String encodeString) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
}

/**
* 删除Cookie带cookie value
*
* @param request
* @param response
* @param cookieName 名称
*/
public static void deleteCookie(HttpServletRequest request,
HttpServletResponse response,
String cookieName) {
doSetCookie(request, response, cookieName, "", -1, false);
}

/**
* 设置Cookie的值,并使其在指定时间内生效
*
* @param request
* @param response
* @param cookieName 名称
* @param cookieValue 设置值
* @param cookieMaxage 生效时间
* @param isEncode 是否编码
*/
private static final void doSetCookie(HttpServletRequest request,
HttpServletResponse response,
String cookieName,
String cookieValue,
int cookieMaxage,
boolean isEncode) {
try {
if (cookieValue == null) {
cookieValue = "";
} else if (isEncode) {
cookieValue = URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0) {
cookie.setMaxAge(cookieMaxage);
}
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
System.out.println(domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 设置Cookie的值,并使其在指定时间内生效
*
* @param request
* @param response
* @param cookieName 名称
* @param cookieValue 值
* @param cookieMaxage 有效时间
* @param encodeString 编码格式
*/
private static final void doSetCookie(HttpServletRequest request,
HttpServletResponse response,
String cookieName,
String cookieValue,
int cookieMaxage,
String encodeString) {
try {
if (cookieValue == null) {
cookieValue = "";
} else {
cookieValue = URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0) {
cookie.setMaxAge(cookieMaxage);
}
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
System.out.println(domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 获得域名或ip地址
*
* @param request
* @return
*/
private static final String getDomainName(HttpServletRequest request) {
String domainName = null;
// 通过request对象获取访问的url地址
String serverName = request.getRequestURL().toString();
if ("".equals(serverName)) {
domainName = "";
} else {
// 将url转换为小写
serverName = serverName.toLowerCase();
// 如果url地址是以http://开头 将http://截取
if (serverName.startsWith("http://")) {
serverName = serverName.substring(7);
}
if (serverName.startsWith("https://")) {
serverName = serverName.substring(8);
}
//截取后的长度
int end = serverName.length();
// 判断url地址是否包含"/"
if (serverName.contains("/")) {
//得到第一个"/"出现的位置
end = serverName.indexOf("/");
}
// 截取
serverName = serverName.substring(0, end);
if(serverName.matches(".*[a-zA-z].*")){
// 根据"."进行分割
final String[] domains = serverName.split("\\.");
int len = domains.length;
if (len > 3) {
// www.xxx.com.cn
domainName = domains[len - 3] + "." + domains[len - 2] + "." +
domains[len - 1];
} else if (len > 1) {
// xxx.com or xxx.cn
domainName = domains[len - 2] + "." + domains[len - 1];
} else {
domainName = serverName;
}
}else{
//127.0.0.1——ip地址情况
domainName = serverName;
}
}
if (domainName.indexOf(":") > 0) {
String[] ary = domainName.split(":");
domainName = ary[0];
}
return domainName;
}
}

电话号码校验工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ValidatorUtil {
/**
* 电话号码正则
*/
private static final Pattern MOBILE_PATTERN = Pattern.compile("[1]([3-9])[0-9]{9}$");

public static boolean isMobile(String mobile){
if (StringUtils.isEmpty(mobile)) {
return false;
}
Matcher matcher = MOBILE_PATTERN.matcher(mobile);
return matcher.matches();
}
}

UUID工具类

1
2
3
4
5
6
7
8
9
/**
* 生成UUID的工具类,去除短横线-
*/
public class UUIDUtil {

public static String uuid() {
return UUID.randomUUID().toString().replace("-", "");
}
}

JSON工具类

基于Jcakson

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
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
* Json工具类
*
*
* @author Hua JFarmer
*/
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();

/**
* 将对象转换成json字符串
*
* @param obj 对象
* @return 字符串
*/
public static String object2JsonStr(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
//打印异常信息
e.printStackTrace();
}
return null;
}

/**
* 将字符串转换为对象
*
* @param jsonStr 对象字符串
* @param clazz 对象类型
* @param <T> 泛型
* @return 对象
*/
public static <T> T jsonStr2Object(String jsonStr, Class<T> clazz) {
try {
return objectMapper.readValue(jsonStr.getBytes(StandardCharsets.UTF_8), clazz);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

/**
* 将json数据转换成pojo对象list
*
* @param jsonStr list字符串
* @param beanType 对象类型
* @param <T> 泛型
* @return list集合
*/
public static <T> List<T> jsonToList(String jsonStr, Class<T> beanType) {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType);
try {
return objectMapper.readValue(jsonStr, javaType);
} catch (Exception e) {
e.printStackTrace();
}

return null;
}
}

JWT工具类

基于jjwt

详情可见 https://github.com/jwtk/jjwt

Maven
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!--jwt-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
代码
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package com.huajframe.security.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author Hua JFarmer
*/
public class JwtUtils {

/**
* 过期时间
*/
private static final long EXPIRE = 60 * 1000;

/**
* 密钥,动态生成的密钥
*/
public static final SecretKey KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

/**
* 生成token
*
* @param claims 要传送消息map
* @return
*/
public static String generate(Map<String,Object> claims) {
Date nowDate = new Date();
//过期时间,设定为一分钟
Date expireDate = new Date(System.currentTimeMillis() + EXPIRE);
//头部信息,可有可无
Map<String, Object> header = new HashMap<>(2);
header.put("typ", "jwt");

//更强的密钥,JDK11起才能用
// KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
// PrivateKey key1 = keyPair.getPrivate(); // 私钥
//PublicKey key2 = keyPair.getPublic(); //公钥

return Jwts.builder().setHeader(header)
// .setSubject("----")//主题
// .setIssuer("----") //发送方
.setClaims(claims) //自定义claims
.setIssuedAt(nowDate)//当前时间
.setExpiration(expireDate) //过期时间
.signWith(KEY)//签名算法和key
.compact();
}

/**
* 生成token
* @param header 传入头部信息map
* @param claims 要传送消息map
* @return
*/
public static String generate( Map<String, Object> header, Map<String,Object> claims) {
Date nowDate = new Date();
//过期时间,设定为一分钟
Date expireDate = new Date(System.currentTimeMillis() + EXPIRE);

return Jwts.builder().setHeader(header)
// .setSubject("--------")//主题
// .setIssuer("-------") //发送方
.setClaims(claims) //自定义claims
.setIssuedAt(nowDate)//当前时间
.setExpiration(expireDate) //过期时间
.signWith(KEY)//签名算法和key
.compact();
}

/**
* 判断是不是jwt签名
* @param token 传入签名
* @return
*/
public static boolean isSigned(String token){
return Jwts.parserBuilder()
.setSigningKey(KEY)
.build()
.isSigned(token);
}

/**
* 校验签名是否正确
* @param token
* @return
*/
public static boolean verify(String token){
try {
Jwts.parserBuilder()
.setSigningKey(KEY)
.build()
.parseClaimsJws(token);
return true;
}catch (JwtException e){
System.out.println(e.getMessage());
return false;
}
}

/**
* 获取payload 部分内容(即要传的信息)
* 使用方法:如获取userId:getClaim(token).get("userId");
* @param token
* @return
*/
public static Claims getClaim(String token) {
Claims claims = null;
try {
claims = Jwts.parserBuilder()
.setSigningKey(KEY)
.build()
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
e.printStackTrace();
}
return claims;
}

/**
* 获取头部信息map
* 使用方法 : getHeader(token).get("alg");
* @param token
* @return
*/
public static JwsHeader getHeader(String token) {
JwsHeader header = null;
try {
header = Jwts.parserBuilder()
.setSigningKey(KEY)
.build()
.parseClaimsJws(token)
.getHeader();
} catch (Exception e) {
e.printStackTrace();
}
return header;
}

/**
* 获取jwt发布时间
*/
public static Date getIssuedAt(String token) {
return getClaim(token).getIssuedAt();
}

/**
* 获取jwt失效时间
*/
public static Date getExpiration(String token) {
return getClaim(token).getExpiration();
}

/**
* 验证token是否失效
*
* @param token
* @return true:过期 false:没过期
*/
public static boolean isExpired(String token) {
try {
final Date expiration = getExpiration(token);
return expiration.before(new Date());
} catch (ExpiredJwtException expiredJwtException) {
return true;
}
}

/**
* 直接Base64解密获取header内容
* @param token
* @return
*/
public static String getHeaderByBase64(String token){
String header = null;
if (isSigned(token)){
try {
byte[] headerByte = Base64.getDecoder().decode(token.split("\\.")[0]);
header = new String(headerByte);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
return header;
}

/**
* 直接Base64解密获取payload内容
* @param token
* @return
*/
public static String getPayloadByBase64(String token){
String payload = null;
if (isSigned(token)) {
try {
byte[] payload_byte = Base64.getDecoder().decode(token.split("\\.")[1]);
payload = new String(payload_byte);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
return payload;
}

public static void main(String[] args) {
//用户自定义信息claims
Map<String,Object> map = new HashMap<>(2);
map.put("userId","123456");
String token = generate(map);
System.out.println(token);

System.out.println("claim:" + getClaim(token).get("userId"));
System.out.println("header:" + getHeader(token));
// System.out.println(getIssuedAt(token));
Claims claims=getClaim(token);

// System.out.println(getHeaderByBase64(token));
System.out.println(getPayloadByBase64(token));

SimpleDateFormat sdf=new SimpleDateFormat("yyyy‐MM‐dd hh:mm:ss");
System.out.println("签发时间:"+sdf.format(claims.getIssuedAt()));
System.out.println("过期时间:"+sdf.format(claims.getExpiration()));
System.out.println("当前时间:"+sdf.format(new Date()) );

}
}


常用工具类
https://huajframe.github.io/2023/02/26/工具/常用工具类/
作者
HuaJFrame
发布于
2023年2月26日
许可协议