Fork me on GitHub

项目开发工具类

在之前的 Java开发过程中,总结了许多的工具类,像类似的工具类其实有很多,这里总结一些自己常用到的。其中有些是借鉴别人的,有些是自己总结的,比如MD5工具类、Password工具类、BigDecimal工具类、DateTime工具类、Properties工具类、FTP服务器工具类、JWT工具类、 Http工具类、Cookie工具类、Json工具类、IP工具类、Redis工具类、下面这些工具类,另外附加几个加密类,使用时直接稍做修改就可以使用了。

MD5
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

import lombok.extern.slf4j.Slf4j;
import java.security.MessageDigest;
@Slf4j
public class MD5Util {

public final static String encrypt(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
log.error("generate md5 error, {}", s, e);
return null;
}
}
}
PasswordUtil
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
import java.util.Date;
import java.util.Random;

public class PasswordUtil {

public final static String[] word = {
"a", "b", "c", "d", "e", "f", "g",
"h", "j", "k", "m", "n",
"p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G",
"H", "J", "K", "M", "N",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"
};

public final static String[] num = {
"2", "3", "4", "5", "6", "7", "8", "9"
};

public static String randomPassword() {
StringBuffer stringBuffer = new StringBuffer();
Random random = new Random(new Date().getTime());
boolean flag = false;
int length = random.nextInt(3) + 8;
for (int i = 0; i < length; i++) {
if (flag) {
stringBuffer.append(num[random.nextInt(num.length)]);
} else {
stringBuffer.append(word[random.nextInt(word.length)]);
}
flag = !flag;
}
return stringBuffer.toString();
}

public static void main(String[] args) throws Exception {
System.out.println(randomPassword());
Thread.sleep(100);
System.out.println(randomPassword());
Thread.sleep(100);
System.out.println(randomPassword());
}
}
BigDecimalUtil
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
import java.math.BigDecimal;
public class BigDecimalUtil
{
private BigDecimalUtil()
{
//私有构造器,不允许实例化
}
//加法
public static BigDecimal add(double v1,double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2);
}
//减法
public static BigDecimal sub(double v1,double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2);
}
//乘法
public static BigDecimal mul(double v1,double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2);
}
//除法
public static BigDecimal div(double v1,double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//四舍五入,保留两位小数

//除不尽的情况
}
}
DateTimeUtil
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
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Date;

public class DateTimeUtil
{
//str->Date
//Date->str
public static final String STANDARD_FDRMAT = "yyyy-MM-dd HH:mm:ss";


public static Date strToDate(String dateTimeStr, String formatStr)
{
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
return dateTime.toDate();
}

public static String dateToStr(Date date,String formatStr)
{
if(date == null)
{
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(formatStr);
}

public static void main(String[] args)
{
System.out.println(DateTimeUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
System.out.println(DateTimeUtil.strToDate("2010-01-01 11:11:11","yyyy-MM-dd HH:mm:ss"));
}

public static Date strToDate(String dateTimeStr)
{
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FDRMAT);
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
return dateTime.toDate();
}

public static String dateToStr(Date date)
{
if(date == null)
{
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(STANDARD_FDRMAT);
}
}
PropertiesUtil
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
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.IIOException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

public class PropertiesUtil
{
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

private static Properties props;

static {
String fileName = "mmall.properties";
props = new Properties();
try
{
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
}catch (IOException e)
{
logger.error("配置文件读取异常",e);
}
}

public static String getProperty(String key )
{
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value))
{
return null;
}
return value.trim();
}
public static String getProperty(String key,String defaultValue)
{
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value))
{
value = defaultValue;
}
return value.trim();
}
}
FTPUtil
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
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
* @author zqnh
* @date 2019/7/28 on 8:50.
*/
public class FTPUtil
{
private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
private static String ftpuser = PropertiesUtil.getProperty("ftp.user");
private static String ftpPass = PropertiesUtil.getProperty("ftp.pass");

private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);

public FTPUtil(String ip,int port,String user,String pwd)
{
this.ip=ip;
this.port=port;
this.user=user;
this.pwd=pwd;
}

public static boolean uploadFile(List<File> fileList) throws IOException
{
FTPUtil ftpUtil = new FTPUtil(ftpIp,21,ftpuser,ftpPass);
logger.info("开始连接ftp服务器");
boolean result=ftpUtil.uploadFile("img",fileList);

logger.info("开始连接ftp服务器,结束上传,上传结果:{}");
return result;
}
private boolean uploadFile(String remotePath,List<File> fileList) throws IOException
{
boolean uploaded = true;
FileInputStream fis = null;
//连接FTP服务器
if(connectServer(this.ip,this.port,this.user,this.pwd))
{
try {
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
for (File fileItem : fileList)
{
fis = new FileInputStream(fileItem);
ftpClient.storeFile(fileItem.getName(),fis);
}
}
catch (IOException e) {
logger.error("上传文件异常",e);
uploaded = false;
e.printStackTrace();
}finally {
fis.close();
ftpClient.disconnect();
}
}
return uploaded;
}
private boolean connectServer(String ip,int port,String user,String pwd)
{
boolean isSuccess = false;
ftpClient = new FTPClient();
try {
ftpClient.connect(ip);
isSuccess = ftpClient.login(user,pwd);
}
catch (IOException e) {
logger.error("连接FTP服务器异常",e);
e.printStackTrace();
}
return isSuccess;
}

private String ip;
private String user;
private int port;
private String pwd;
private FTPClient ftpClient;

public String getIp()
{
return ip;
}

public void setIp(String ip)
{
this.ip = ip;
}

public String getUser()
{
return user;
}

public void setUser(String user)
{
this.user = user;
}

public int getPort()
{
return port;
}

public void setPort(int port)
{
this.port = port;
}

public String getPwd()
{
return pwd;
}

public void setPwd(String pwd)
{
this.pwd = pwd;
}

public FTPClient getFtpClient()
{
return ftpClient;
}

public void setFtpClient(FTPClient ftpClient)
{
this.ftpClient = ftpClient;
}
}
JWT工具类
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
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import net.zzqd.elearning.domain.User;
import java.util.Date;

public class JwtUtils
{
public static final String SUBJECT="elea";
public static final long EXPIRE = 1000 * 60 * 60 * 24 * 7;//过期时间,毫秒, 一周

//密钥
public static final String APPSECRE = "elea64";

/**
* 生成jwt
* @param user
* @return
*/
public static String geneJsonWebToken(User user)
{
if(user == null || user.getId()==null || user.getName()==null || user.getHeadImg()==null)
{
return null;
}
String token = Jwts.builder().setSubject(SUBJECT)
.claim("id",user.getId())
.claim("name",user.getName())
.claim("img",user.getHeadImg())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
.signWith(SignatureAlgorithm.HS256,APPSECRE).compact();

return token;
}

/**
* 校验token
* @param token
* @return
*/
public static Claims checkJWT(String token)
{
try {
final Claims claims = Jwts.parser().setSigningKey(APPSECRE)
.parseClaimsJws(token).getBody();
return claims;
}catch (Exception e)
{
return null;
}

}
}
HttpUtil
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

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.util.HashMap;
import java.util.Map;

/**
* @author zqnh
* @date 2019/7/18 on 15:27.
* 封装Http get post 方法
*/
public class HttpUtils
{

private static final Gson gson = new Gson();
/**
* get方法
* @param url
* @return
*/
public static Map<String,Object> doGet(String url)
{
Map<String,Object> map = new HashMap<>();
CloseableHttpClient httpClient = HttpClients.createDefault();

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)//超时时间
.setConnectionRequestTimeout(5000)//请求超时
.setSocketTimeout(5000)
.setRedirectsEnabled(true)//允许自动重定向
.build();

HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);

try{
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200)
{
String jsonResult = EntityUtils.toString(httpResponse.getEntity());
map = gson.fromJson(jsonResult,map.getClass());
}
}catch (Exception e)
{
e.printStackTrace();
}finally {
try{
httpClient.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
return map;
}

/**
* 封装post
* @return
*/
public static String doPost(String url,String data,int timeout)
{

CloseableHttpClient httpClient = HttpClients.createDefault();
//超时设置
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)//超时时间
.setConnectionRequestTimeout(timeout)//请求超时
.setSocketTimeout(timeout)
.setRedirectsEnabled(true)//允许自动重定向
.build();

HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-Type","text/html;charset=UTF-8");
if(data!=null && data instanceof String)//使用字符串传参
{
StringEntity stringEntity = new StringEntity(data,"UTF-8");
httpPost.setEntity(stringEntity);

}

try{
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if(httpResponse.getStatusLine().getStatusCode()==200)
{
String result = EntityUtils.toString(httpEntity);
return result;
}
}catch (Exception e)
{
try{
httpClient.close();
}catch (Exception e1)
{
e1.printStackTrace();
}
}
return null;
}
}
CookieUtil
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

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CookieUtil {
private final static String COOKIE_DOMAIN = "localhost";
private final static String COOKIE_NAME = "seckill_login_token";


public static String readLoginToken(HttpServletRequest request){
Cookie[] cks = request.getCookies();
if(cks != null){
for(Cookie ck : cks){
log.info("read cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
if(StringUtils.equals(ck.getName(),COOKIE_NAME)){
log.info("return cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
return ck.getValue();
}
}
}
return null;
}

//X:domain=".hfbin.cn"
//a:A.hfbin.cn cookie:domain=A.hfbin.cn;path="/"
//b:B.hfbin.cn cookie:domain=B.hfbin.cn;path="/"
//c:A.hfbin.cn/test/cc cookie:domain=A.hfbin.cn;path="/test/cc"
//d:A.hfbin.cn/test/dd cookie:domain=A.hfbin.cn;path="/test/dd"
//e:A.hfbin.cn/test cookie:domain=A.hfbin.cn;path="/test"

public static void writeLoginToken(HttpServletResponse response, String token){
Cookie ck = new Cookie(COOKIE_NAME,token);
ck.setDomain(COOKIE_DOMAIN);
ck.setPath("/");//代表设置在根目录
ck.setHttpOnly(true);
//单位是秒。
//如果这个maxage不设置的话,cookie就不会写入硬盘,而是写在内存。只在当前页面有效。
ck.setMaxAge(60 * 60 * 24 * 365);//如果是-1,代表永久
log.info("write cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
response.addCookie(ck);
}

public static void delLoginToken(HttpServletRequest request, HttpServletResponse response){
Cookie[] cks = request.getCookies();
if(cks != null){
for(Cookie ck : cks){
if(StringUtils.equals(ck.getName(),COOKIE_NAME)){
ck.setDomain(COOKIE_DOMAIN);
ck.setPath("/");
ck.setMaxAge(0);//设置成0,代表删除此cookie。
// log.info("del cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
response.addCookie(ck);
return;
}
}
}
}
}
JsonUtil
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

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();

static{
//序列化需要配置的

//对象所有字段全部列入
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.ALWAYS);

//取消默认转换timestamps形式
objectMapper.configure(SerializationConfig.Feature.WRITE_DATE_KEYS_AS_TIMESTAMPS , false);

//忽略空Bean转换Json的错误
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS ,false);

//所有日期格式都是统一为以下样式,即yyyy-MM-dd HH:mm:ss
objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));

//反序列化需要配置的

//忽视在json字符串中存在,但是在java对象中不存在对应的情况,防止错误
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false) ;
}

/**
* 未格式化好的string 显示成一行
* @param obj
* @param <T>
* @return
*/
public static <T> String obj2String(T obj){
if(obj == null){
return null;
}
try {
return obj instanceof String ? (String)obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to String error",e);
return null;
}
}

/**
* 格式化好的string 按属性分行 一般不用因为格式化好的占字节空间
* @param obj
* @param <T>
* @return
*/
public static <T> String obj2StringPretty(T obj){
if(obj == null){
return null;
}
try {
return obj instanceof String ? (String)obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to String error",e);
return null;
}
}


/**
* <T>将此方法声明为泛型方法 T返回值的类型
* @param str
* @param clazz
* @param <T>
* @return
*/
public static <T> T string2Obj(String str,Class<T> clazz){
if(StringUtils.isEmpty(str) || clazz == null){
return null;
}

try {
return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz);
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}


/**
*
* @param str
* @param typeReference
* @param <T>
* @return
*/
public static <T> T string2Obj(String str, TypeReference<T> typeReference){
if(StringUtils.isEmpty(str) || typeReference == null){
return null;
}
try {
return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}


/**
* Class 为什么使用 <?> 因为未确认集合类型与集合里面元素类型 (集合类型与集合里面元素类型是不一样的类型,所以不能用同一个T)
* @param str
* @param collectionClass 集合类型
* @param elementClasses 集合里面元素类型
* @param <T>
* @return
*/
public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
try {
return objectMapper.readValue(str,javaType);
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
public static void main(String[] args) {


}
}
IPUtil
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
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
/**
* IP地址
*/
public class IPUtils {

private static Logger logger = LoggerFactory.getLogger(IPUtils.class);

/**
* 获取IP地址
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IPUtils ERROR ", e);
}
// 使用代理,则获取第一个IP地址
if (StringUtils.isNotEmpty(ip) && ip.length() > 15) {
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}
}
RedisUtil
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
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
@Component
public class RedisUtil {

private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);

@Resource
private RedisTemplate<Serializable, Serializable> redisTemplate;

/**
* 前缀
*/
public static final String KEY_PREFIX_VALUE = "itstyle:seckill:value:";


/**
* 缓存value操作
* @param k
* @param v
* @param time
* @return
*/
public boolean cacheValue(String k, Serializable v, long time) {
String key = KEY_PREFIX_VALUE + k;
try {
ValueOperations<Serializable, Serializable> valueOps = redisTemplate.opsForValue();
valueOps.set(key, v);
if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
return true;
} catch (Throwable t) {
logger.error("缓存[{}]失败, value[{}]",key,v,t);
}
return false;
}
public boolean cacheValue(String k, Serializable v, long time,TimeUnit unit) {
String key = KEY_PREFIX_VALUE + k;
try {
ValueOperations<Serializable, Serializable> valueOps = redisTemplate.opsForValue();
valueOps.set(key, v);
if (time > 0) redisTemplate.expire(key, time, unit);
return true;
} catch (Throwable t) {
logger.error("缓存[{}]失败, value[{}]",key,v,t);
}
return false;
}

/**
* 缓存value操作
* @param k
* @param v
* @return
*/
public boolean cacheValue(String k, Serializable v) {
return cacheValue(k, v, -1);
}

/**
* 判断缓存是否存在
* @param k
* @return
*/
public boolean containsValueKey(String k) {
String key = KEY_PREFIX_VALUE + k;
try {
return redisTemplate.hasKey(key);
} catch (Throwable t) {
logger.error("判断缓存存在失败key[" + key + ", error[" + t + "]");
}
return false;
}
/**
* 获取缓存
* @param k
* @return
*/
public Serializable getValue(String k) {
try {
ValueOperations<Serializable, Serializable> valueOps = redisTemplate.opsForValue();
return valueOps.get(KEY_PREFIX_VALUE + k);
} catch (Throwable t) {
logger.error("获取缓存失败key[" + KEY_PREFIX_VALUE + k + ", error[" + t + "]");
}
return null;
}
/**
* 移除缓存
* @param k
* @return
*/
public boolean removeValue(String k) {
String key = KEY_PREFIX_VALUE + k;
try {
redisTemplate.delete(key);
return true;
} catch (Throwable t) {
logger.error("获取缓存失败key[" + key + ", error[" + t + "]");
}
return false;
}
}
Base64Encoder
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
public class Base64Encoder {
public static String getBASE64(String s) {
if (s == null)
return null;
return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
}
// 将 BASE64 编码的字符串 s 进行解码 解密
public static String getFromBASE64(String s) {
if (s == null)
return null;
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(s);
return new String(b);
} catch (Exception e) {
return null;
}
}
public static String mTOa(Object ming){
return Base64Encoder.getBASE64(Base64Encoder.getBASE64(Base64Encoder.getBASE64((String)ming)));
}
public static String aTOm(String an){
return Base64Encoder.getFromBASE64(Base64Encoder.getFromBASE64(Base64Encoder.getFromBASE64(an)));
}
public static void main(String[] args) {
String a = mTOa("123".toString());
System.out.println(a);//加密
System.out.println(aTOm(a));//解密
}
}
SecurityAES
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
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
/**
* AES对称加密
*
*/
public class SecurityAES {
private final static String encoding = "UTF-8";
private static String PASSWORD = "qwedcxza";


/**
* AES加密
*
*/
public static String encryptAES(String content) {
byte[] encryptResult = encrypt(content);
String encryptResultStr = parseByte2HexStr(encryptResult);
// BASE64位加密
encryptResultStr = ebotongEncrypto(encryptResultStr);
return encryptResultStr;
}
/**
* AES解密
* @Author 张志朋
*
*/
public static String decrypt(String encryptResultStr) {
// BASE64位解密
String decrpt = ebotongDecrypto(encryptResultStr);
byte[] decryptFrom = parseHexStr2Byte(decrpt);
byte[] decryptResult = decrypt(decryptFrom);
return new String(decryptResult);
}
/**
* 加密字符串
*
*/
public static String ebotongEncrypto(String str) {
String result = str;
if (str != null && str.length() > 0) {
try {
byte[] encodeByte = str.getBytes(encoding);
//阿里巴巴
//result = Base64.byteArrayToBase64(encodeByte);
result = new String(Base64.encodeBase64(encodeByte),"Utf-8");
} catch (Exception e) {
e.printStackTrace();
}
}
//base64加密超过一定长度会自动换行 需要去除换行符
return result.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
}
/**
* 解密字符串
*
*/
public static String ebotongDecrypto(String str) {
try {
//byte[] encodeByte = Base64.base64ToByteArray(str);//阿里巴巴
byte[] encodeByte = Base64.decodeBase64(str.getBytes("Utf-8"));

return new String(encodeByte);
} catch (Exception e) {
e.printStackTrace();
return str;
}
}
/**
* 加密
*
*/
private static byte[] encrypt(String content) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
//防止linux下 随机生成key
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
secureRandom.setSeed(PASSWORD.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
*
*/
private static byte[] decrypt(byte[] content) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
//防止linux下 随机生成key
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
secureRandom.setSeed(PASSWORD.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将二进制转换成16进制
*
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
public static void main(String[] args) {
String str = encryptAES("1234567890");
System.out.println(str);
str = decrypt(str);
System.out.println(str);
}
}
SecurityBase64
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
import java.io.UnsupportedEncodingException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
* Base64 也会经常用作一个简单的“加密”来保护某些数据,而真正的加密通常都比较繁琐。
*/
public class SecurityBase64 {
// 加密
public String getBase64(String str) {
byte[] b = null;
String s = null;
try {
b = str.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (b != null) {
s = new BASE64Encoder().encode(b);
}
return s;
}

// 解密
public String getFromBase64(String s) {
byte[] b = null;
String result = null;
if (s != null) {
BASE64Decoder decoder = new BASE64Decoder();
try {
b = decoder.decodeBuffer(s);
result = new String(b, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}

public static void main(String args[]){
SecurityBase64 b6 = new SecurityBase64();
System.out.println(b6.getBase64("ILoveYou"));//加密
System.out.println(b6.getFromBase64(b6.getBase64("ILoveYou")));//解密
}

}
SecurityDES
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
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

/**
* 对称加密
* 这里面的API里面有很多是调用getInstance方法,这个方法的参数有algorithm或者transformation
* 一:algorithm:算法
*
* 二:transformation:有两种格式
* 1:算法/模式/填充方式。如:DES/CBC/PKCS5Padding
* 2:算法。 如:DES
*
* 其中,algorithm、transformation的值,不区分大小写
*
* Java加密解密官方参考文档:
* https://docs.oracle.com/javase/8/docs/technotes/guides/security/index.html
* https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html
*/
public class SecurityDES {
/*
* 使用KeyGenerator生成key
*
* 其中,algorithm支持的算法有:AES、DES、DESEDE、HMACMD5、HMACSHA1、HMACSHA256、RC2等
* 全部支持的算法见官方文档
* https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyGenerator
*
*/
public static Key newKeyByKeyGenerator(String algorithm) throws NoSuchAlgorithmException {
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
Key key = kg.generateKey();
return key;
}

/**
* 使用SecretKeySpec生成key
* 一般是从一个文件中读取出key的byte数组,然后根据文件key的算法,构建出key对象
*/
public static Key newKeyBySecretKeySpec(byte[] key, String algorithm) throws NoSuchAlgorithmException {
return new SecretKeySpec(key, algorithm);
}

/**
* 加密,对字符串进行加密,返回结果为byte数组
* 保存的时候,可以把byte数组进行base64编码成字符串,或者把byte数组转换成16进制的字符串
*
* 其中,transformation支持的全部算法见官方文档:
* https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#Cipher
*/
public static byte[] encrypt(String transformation, Key key, String password) throws Exception {
Cipher cipher = Cipher.getInstance(transformation);
//加密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(password.getBytes());
}

/**
* 解密,返回结果为原始字符串
*
* 其中,transformation支持的全部算法见官方文档:
* https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#Cipher
*/
public static String decrypt(String transformation, Key key, byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance(transformation);
//解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(data);
String password = new String(result);
return password;
}

public static void main(String[] args) throws Exception {
String password = "123456";

String algorithm = "DES";
String transformation = algorithm;

//加密解密使用的都是同一个秘钥key
Key key = newKeyByKeyGenerator(algorithm);
System.out.println(" 秘钥: " + key);
//加密
byte[] passData = encrypt(transformation, key, password);
//解密
String pass = decrypt(transformation, key, passData);

System.out.println("解密后的密码 : " + pass);
}
}
SecurityRSA
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
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;

/**
* RSA公钥加密
*/
public class SecurityRSA {
public static void makekeyfile(String pubkeyfile, String privatekeyfile)
throws NoSuchAlgorithmException, FileNotFoundException, IOException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为1024位
keyPairGen.initialize(1024);
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();

// 得到私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

// 得到公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

// 生成私钥
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
privatekeyfile));
oos.writeObject(privateKey);
oos.flush();
oos.close();

oos = new ObjectOutputStream(new FileOutputStream(pubkeyfile));
oos.writeObject(publicKey);
oos.flush();
oos.close();

System.out.println("make file ok!");
}

/**
*
* @param k
* @param data
* @param encrypt
* 1 加密 0解密
* @return
* @throws NoSuchPaddingException
* @throws Exception
*/
public static byte[] handleData(Key k, byte[] data, int encrypt)
throws Exception {

if (k != null) {

Cipher cipher = Cipher.getInstance("RSA");

if (encrypt == 1) {
cipher.init(Cipher.ENCRYPT_MODE, k);
byte[] resultBytes = cipher.doFinal(data);
return resultBytes;
} else if (encrypt == 0) {
cipher.init(Cipher.DECRYPT_MODE, k);
byte[] resultBytes = cipher.doFinal(data);
return resultBytes;
} else {
System.out.println("参数必须为: 1 加密 0解密");
}
}
return null;
}

public static void main(String[] args) throws Exception {
//创建目录
String pubfile = "d:/temp/pub.key";
String prifile = "d:/temp/pri.key";

makekeyfile(pubfile, prifile);

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(pubfile));
RSAPublicKey pubkey = (RSAPublicKey) ois.readObject();
ois.close();

ois = new ObjectInputStream(new FileInputStream(prifile));
RSAPrivateKey prikey = (RSAPrivateKey) ois.readObject();
ois.close();

// 使用公钥加密
String msg = "爪哇笔记-秒杀项目";
String enc = "UTF-8";

// 使用公钥加密私钥解密
System.out.println("原文: " + msg);
byte[] result = handleData(pubkey, msg.getBytes(enc), 1);
System.out.println("加密: " + new String(result, enc));
byte[] deresult = handleData(prikey, result, 0);
System.out.println("解密: " + new String(deresult, enc));

msg = "秒杀项目";
// 使用私钥加密公钥解密
System.out.println("原文: " + msg);
byte[] result2 = handleData(prikey, msg.getBytes(enc), 1);
System.out.println("加密: " + new String(result2, enc));
byte[] deresult2 = handleData(pubkey, result2, 0);
System.out.println("解密: " + new String(deresult2, enc));

}
}