Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
J
jz-dmp-service
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
姚本章
jz-dmp-service
Commits
7d574b89
Commit
7d574b89
authored
Dec 18, 2020
by
sml
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
初稿提交
parents
Pipeline
#325
failed with stages
Changes
19
Pipelines
2
Expand all
Hide whitespace changes
Inline
Side-by-side
Showing
19 changed files
with
1691 additions
and
0 deletions
+1691
-0
Constants.java
src/main/java/com/jz/common/constant/Constants.java
+33
-0
JsonResult.java
src/main/java/com/jz/common/constant/JsonResult.java
+60
-0
ResultCode.java
src/main/java/com/jz/common/constant/ResultCode.java
+60
-0
GlobalExceptionHandler.java
.../java/com/jz/common/exception/GlobalExceptionHandler.java
+141
-0
ServiceException.java
src/main/java/com/jz/common/exception/ServiceException.java
+11
-0
LoginFilter.java
src/main/java/com/jz/common/filter/LoginFilter.java
+197
-0
JwtUserInfo.java
src/main/java/com/jz/common/jwt/JwtUserInfo.java
+40
-0
JwtUtil.java
src/main/java/com/jz/common/jwt/JwtUtil.java
+174
-0
PatternMatcher.java
src/main/java/com/jz/common/service/PatternMatcher.java
+5
-0
ServletPathMatcher.java
src/main/java/com/jz/common/service/ServletPathMatcher.java
+44
-0
DateUtils.java
src/main/java/com/jz/common/utils/DateUtils.java
+0
-0
IpUtil.java
src/main/java/com/jz/common/utils/IpUtil.java
+201
-0
MD5SignUtils.java
src/main/java/com/jz/common/utils/MD5SignUtils.java
+77
-0
PasswordUtil.java
src/main/java/com/jz/common/utils/PasswordUtil.java
+100
-0
RSAUtils.java
src/main/java/com/jz/common/utils/RSAUtils.java
+234
-0
StringUtils.java
src/main/java/com/jz/common/utils/StringUtils.java
+199
-0
toolsController.java
...n/java/com/jz/dmp/modules/controller/toolsController.java
+32
-0
AtomBaseCacheService.java
...java/com/jz/dmp/modules/service/AtomBaseCacheService.java
+21
-0
AtomBaseCacheServiceImpl.java
...jz/dmp/modules/service/impl/AtomBaseCacheServiceImpl.java
+62
-0
No files found.
src/main/java/com/jz/common/constant/Constants.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
constant
;
public
class
Constants
{
/**
* 数据状?(1:正常;0:删除;?
*/
public
static
final
String
DATA_STATE_NORMAL
=
"1"
;
public
static
final
String
DATA_STATE_DELETE
=
"0"
;
//access_token 过期时间
public
static
final
long
ACCESS_EXPIRE
=
60
*
10
;
//refresh_token 过期时间 暂时没用
public
static
final
long
REFRESH_EXPIRE
=
60
*
10
;
public
static
final
String
privateKey
=
"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAK1VxmLOUE9ps4m8Xked9nIMMkqK"
+
"Cn77VqC9VmEcSPcp7w38XumXed45vnRkf6+kxuooiazfqfbzqkyURRDOaXIVspzC1LbZxwArhjvE"
+
"qurq9zEDu6m7+gZR6G763wRqQHMcQAoH8JJDpiLZRF7Wr3AhOCPxVEUEWNfTwbTbjM4LAgMBAAEC"
+
"gYA25BzpGVDRdTXH/oEUyO9MepRKiqB8SffK+2qpYh2xN/ReR3d/HdsYBs1LarAM3W+oo6HFvybB"
+
"77QUgDfG9LbrRMJJL4W3yrcLP5LlzjvW1kcCazVyRZPpETsJOaOc8Juhb0Yz6tmrGf2rWvktpdJ4"
+
"L9uzlyZ9hWPms0eyw38JMQJBAPgbZnpEKza+gtqgdFZZ4NIXx6ypL2cx+aAtQB0W0baaT9jJb8Jb"
+
"84e3XvxlFjzCYBaoCDgyHwPKphK5LSJFINUCQQCy2W1Gbo8JNKyAgj5TeuQg8RELMGit9gbCaCNv"
+
"kjA7ZpASTPHvj8K7VMI6BPJqtNCo/qLtuo0THUdmUShvBqNfAkBJT6dfN2dhfLejrEfUACjLS5WH"
+
"slI8durg5p4MOmLrRvuS/iqUzqDOGGPrxl7kwzarWylamYzKjQW3gJoSh0SlAkBhf5RJtBW30AZG"
+
"HDp76d+ZcbF35xD53Mg8jObceNZgW34o69dsYHOpCgDD/lRlBWNG7WHGtU8Y33o/9fhT5kuDAkBg"
+
"0mOxtUf/4fs8djLeBWP8v/MMMybro4BbM7YgO/xgK4/135XhkAMdcY+xyR28ruVF7WHJujFYunXD"
+
"/TfrZUrw"
;
public
static
final
String
publicKey
=
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCtVcZizlBPabOJvF5HnfZyDDJKigp++1agvVZh"
+
"HEj3Ke8N/F7pl3neOb50ZH+vpMbqKIms36n286pMlEUQzmlyFbKcwtS22ccAK4Y7xKrq6vcxA7up"
+
"u/oGUehu+t8EakBzHEAKB/CSQ6Yi2URe1q9wITgj8VRFBFjX08G024zOCwIDAQAB"
;
}
src/main/java/com/jz/common/constant/JsonResult.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
constant
;
public
class
JsonResult
{
private
String
code
;
private
String
message
;
private
Object
data
;
public
JsonResult
()
{
this
.
setCode
(
ResultCode
.
SUCCESS
);
this
.
setMessage
(
"成功?"
);
}
public
JsonResult
(
ResultCode
code
)
{
this
.
setCode
(
code
);
this
.
setMessage
(
code
.
msg
());
}
public
JsonResult
(
ResultCode
code
,
String
message
)
{
this
.
setCode
(
code
);
this
.
setMessage
(
message
);
}
public
JsonResult
(
ResultCode
code
,
Object
data
)
{
this
.
setCode
(
code
);
this
.
setMessage
(
code
.
msg
());
this
.
setData
(
data
);
}
public
JsonResult
(
ResultCode
code
,
String
message
,
Object
data
)
{
this
.
setCode
(
code
);
this
.
setMessage
(
message
);
this
.
setData
(
data
);
}
public
String
getCode
()
{
return
code
;
}
public
void
setCode
(
ResultCode
code
)
{
this
.
code
=
code
.
val
();
}
public
String
getMessage
()
{
return
message
;
}
public
void
setMessage
(
String
message
)
{
this
.
message
=
message
;
}
public
Object
getData
()
{
return
data
;
}
public
void
setData
(
Object
data
)
{
this
.
data
=
data
;
}
}
src/main/java/com/jz/common/constant/ResultCode.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
constant
;
public
enum
ResultCode
{
/** 成功 */
SUCCESS
(
"200"
,
"成功"
),
/** 没有登录 */
NOT_LOGIN
(
"400"
,
"没有登录"
),
/** 发生异常 */
EXCEPTION
(
"401"
,
"发生异常"
),
/** 系统错误 */
SYS_ERROR
(
"402"
,
"系统错误"
),
/** 参数错误 */
PARAMS_ERROR
(
"403"
,
"参数错误 "
),
PARAMS_ERROR_TOKEN
(
"446"
,
"token无效"
),
/** 不支持当前请求方? */
METHOD_NOT_ALLOWED
(
"405"
,
"不支持当前请求方? "
),
/** 不支持或已经废弃 */
NOT_SUPPORTED
(
"410"
,
"不支持或已经废弃"
),
/** 不支持当前媒体类? */
UNSUPPORTED_MEDIA_TYPE
(
"415"
,
"不支持当前媒体类?"
),
/** AuthCode错误 */
INVALID_AUTHCODE
(
"444"
,
"无权限访?"
),
/** 太频繁的调用 */
TOO_FREQUENT
(
"445"
,
"太频繁的调用"
),
/** 未知的错? */
UNKNOWN_ERROR
(
"499"
,
"未知错误"
),
/** 内部服务出错 */
INTERNAL_SERVER_ERROR
(
"500"
,
"内部服务出错-逻辑异常"
);
private
String
val
;
private
String
msg
;
private
ResultCode
(
String
value
,
String
msg
)
{
this
.
val
=
value
;
this
.
msg
=
msg
;
}
public
String
val
()
{
return
val
;
}
public
String
msg
()
{
return
msg
;
}
}
src/main/java/com/jz/common/exception/GlobalExceptionHandler.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
exception
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.dao.DataIntegrityViolationException
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.converter.HttpMessageNotReadableException
;
import
org.springframework.validation.BindException
;
import
org.springframework.validation.BindingResult
;
import
org.springframework.validation.FieldError
;
import
org.springframework.web.HttpMediaTypeNotSupportedException
;
import
org.springframework.web.HttpRequestMethodNotSupportedException
;
import
org.springframework.web.bind.MethodArgumentNotValidException
;
import
org.springframework.web.bind.MissingServletRequestParameterException
;
import
org.springframework.web.bind.annotation.ControllerAdvice
;
import
org.springframework.web.bind.annotation.ExceptionHandler
;
import
org.springframework.web.bind.annotation.ResponseBody
;
import
org.springframework.web.bind.annotation.ResponseStatus
;
import
com.jz.common.constant.JsonResult
;
import
com.jz.common.constant.ResultCode
;
import
io.micrometer.core.instrument.config.validate.ValidationException
;
@ControllerAdvice
@ResponseBody
public
class
GlobalExceptionHandler
{
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
GlobalExceptionHandler
.
class
);
/**
* 403 - Bad Request
*/
@ResponseStatus
(
HttpStatus
.
BAD_REQUEST
)
@ExceptionHandler
(
MissingServletRequestParameterException
.
class
)
public
JsonResult
handleMissingServletRequestParameterException
(
MissingServletRequestParameterException
e
)
{
logger
.
error
(
"缺少请求参数"
,
e
);
return
new
JsonResult
(
ResultCode
.
PARAMS_ERROR
,
"required_parameter_is_not_present"
);
}
/**
* 403 - Bad Request
*/
@ResponseStatus
(
HttpStatus
.
BAD_REQUEST
)
@ExceptionHandler
(
HttpMessageNotReadableException
.
class
)
public
JsonResult
handleHttpMessageNotReadableException
(
HttpMessageNotReadableException
e
)
{
logger
.
error
(
"参数解析失败"
,
e
);
return
new
JsonResult
(
ResultCode
.
PARAMS_ERROR
,
"could_not_read_json"
);
}
/**
* 403 - Bad Request
*/
@ResponseStatus
(
HttpStatus
.
BAD_REQUEST
)
@ExceptionHandler
(
MethodArgumentNotValidException
.
class
)
public
JsonResult
handleMethodArgumentNotValidException
(
MethodArgumentNotValidException
e
)
{
logger
.
error
(
"参数验证失败"
,
e
);
BindingResult
result
=
e
.
getBindingResult
();
FieldError
error
=
result
.
getFieldError
();
String
field
=
error
.
getField
();
String
code
=
error
.
getDefaultMessage
();
String
message
=
String
.
format
(
"%s:%s"
,
field
,
code
);
return
new
JsonResult
(
ResultCode
.
PARAMS_ERROR
,
message
);
}
/**
* 403 - Bad Request
*/
@ResponseStatus
(
HttpStatus
.
BAD_REQUEST
)
@ExceptionHandler
(
BindException
.
class
)
public
JsonResult
handleBindException
(
BindException
e
)
{
logger
.
error
(
"参数绑定失败"
,
e
);
BindingResult
result
=
e
.
getBindingResult
();
FieldError
error
=
result
.
getFieldError
();
String
field
=
error
.
getField
();
String
code
=
error
.
getDefaultMessage
();
String
message
=
String
.
format
(
"%s:%s"
,
field
,
code
);
//return new AjaxResult().failure(message);
return
new
JsonResult
(
ResultCode
.
PARAMS_ERROR
,
message
);
}
/**
* 403 - Bad Request
*/
@ResponseStatus
(
HttpStatus
.
BAD_REQUEST
)
@ExceptionHandler
(
ValidationException
.
class
)
public
JsonResult
handleValidationException
(
ValidationException
e
)
{
logger
.
error
(
"参数验证失败"
,
e
);
return
new
JsonResult
(
ResultCode
.
PARAMS_ERROR
,
"validation_exception:"
);
}
/**
* 405 - Method Not Allowed
*/
@ResponseStatus
(
HttpStatus
.
METHOD_NOT_ALLOWED
)
@ExceptionHandler
(
HttpRequestMethodNotSupportedException
.
class
)
public
JsonResult
handleHttpRequestMethodNotSupportedException
(
HttpRequestMethodNotSupportedException
e
)
{
logger
.
error
(
"不支持当前请求方�?"
,
e
);
return
new
JsonResult
(
ResultCode
.
NOT_SUPPORTED
,
"request_method_not_supported:"
);
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus
(
HttpStatus
.
UNSUPPORTED_MEDIA_TYPE
)
@ExceptionHandler
(
HttpMediaTypeNotSupportedException
.
class
)
public
JsonResult
handleHttpMediaTypeNotSupportedException
(
Exception
e
)
{
logger
.
error
(
"不支持当前媒体类�?"
,
e
);
return
new
JsonResult
(
ResultCode
.
UNSUPPORTED_MEDIA_TYPE
,
"content_type_not_supported:"
);
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus
(
HttpStatus
.
INTERNAL_SERVER_ERROR
)
@ExceptionHandler
(
ServiceException
.
class
)
public
JsonResult
handleServiceException
(
ServiceException
e
)
{
logger
.
error
(
"业务逻辑异常"
,
e
);
return
new
JsonResult
(
ResultCode
.
INTERNAL_SERVER_ERROR
,
"业务逻辑异常�?"
);
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus
(
HttpStatus
.
INTERNAL_SERVER_ERROR
)
@ExceptionHandler
(
Exception
.
class
)
public
JsonResult
handleException
(
Exception
e
)
{
logger
.
error
(
"通用逻辑异常"
,
e
);
return
new
JsonResult
(
ResultCode
.
INTERNAL_SERVER_ERROR
,
"参数错误"
);
}
/**
* 操作数据库出现异�?:名称重复,外键关�?
*/
@ResponseStatus
(
HttpStatus
.
INTERNAL_SERVER_ERROR
)
@ExceptionHandler
(
DataIntegrityViolationException
.
class
)
public
JsonResult
handleException
(
DataIntegrityViolationException
e
)
{
logger
.
error
(
"操作数据库出现异�?:"
,
e
);
return
new
JsonResult
(
ResultCode
.
NOT_SUPPORTED
,
"操作数据库出现异常:字段重复、有外键关联�?"
);
}
}
src/main/java/com/jz/common/exception/ServiceException.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
exception
;
public
class
ServiceException
extends
Exception
{
private
static
final
long
serialVersionUID
=
1859731705152111160L
;
public
ServiceException
(
String
message
)
{
super
(
message
);
}
}
src/main/java/com/jz/common/filter/LoginFilter.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
filter
;
import
java.io.IOException
;
import
java.util.Arrays
;
import
java.util.HashMap
;
import
java.util.HashSet
;
import
java.util.Iterator
;
import
java.util.Map
;
import
java.util.Set
;
import
javax.servlet.Filter
;
import
javax.servlet.FilterChain
;
import
javax.servlet.FilterConfig
;
import
javax.servlet.ServletException
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletResponse
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.stereotype.Component
;
import
com.alibaba.fastjson.JSONObject
;
import
com.alibaba.fastjson.serializer.SerializerFeature
;
import
com.jz.common.service.PatternMatcher
;
import
com.jz.common.service.ServletPathMatcher
;
import
com.jz.dmp.modules.service.AtomBaseCacheService
;
import
lombok.extern.slf4j.Slf4j
;
import
nl.bitwalker.useragentutils.Browser
;
import
nl.bitwalker.useragentutils.OperatingSystem
;
import
nl.bitwalker.useragentutils.UserAgent
;
/**
*
* @ClassName: LoginFilter
* @Description: TODO(这里用一句话描述这个类的作用)
* @author: niulichang
* @date: 2020年6月10日 下午4:27:06
* @最后修改人: niulichang
* @最后修改时间: 2020年6月10日 下午4:27:06
*/
@Component
@Slf4j
public
class
LoginFilter
implements
Filter
{
@Autowired
private
AtomBaseCacheService
<
String
>
cacheService
;
public
static
final
String
PARAM_NAME_EXCLUSIONS
=
"exclusions"
;
private
Set
<
String
>
excludesPattern
;
protected
String
contextPath
;
protected
PatternMatcher
pathMatcher
=
new
ServletPathMatcher
();
public
String
getContextPath
()
{
return
contextPath
;
}
public
void
setContextPath
(
String
contextPath
)
{
this
.
contextPath
=
contextPath
;
}
@Override
public
void
init
(
FilterConfig
filterConfig
)
throws
ServletException
{
String
param
=
filterConfig
.
getInitParameter
(
PARAM_NAME_EXCLUSIONS
);
if
(
param
!=
null
&&
param
.
trim
().
length
()
!=
0
)
{
this
.
excludesPattern
=
new
HashSet
(
Arrays
.
asList
(
param
.
split
(
"\\s*,\\s*"
)));
}
}
@Override
public
void
doFilter
(
ServletRequest
request
,
ServletResponse
response
,
FilterChain
chain
)
throws
IOException
,
ServletException
{
HttpServletRequest
httpRequest
=
(
HttpServletRequest
)
request
;
HttpServletResponse
httpResponse
=
(
HttpServletResponse
)
response
;
String
ua
=
httpRequest
.
getHeader
(
"User-Agent"
);
UserAgent
userAgent
=
UserAgent
.
parseUserAgentString
(
ua
);
Browser
browser
=
userAgent
.
getBrowser
();
OperatingSystem
os
=
userAgent
.
getOperatingSystem
();
String
system
=
os
.
getName
();
String
browserName
=
browser
.
getName
();
String
token
=
httpRequest
.
getHeader
(
"token"
);
httpResponse
.
setHeader
(
"Access-Control-Allow-Origin"
,
"http://zhijie-admin.9zdata.cn"
);
//允许来之域名为http://localhost的请求
httpResponse
.
setHeader
(
"Access-Control-Allow-Headers"
,
"Origin,No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, userId, token"
);
httpResponse
.
setHeader
(
"Access-Control-Allow-Methods"
,
"POST, GET, OPTIONS, DELETE"
);
//请求允许的方法
httpResponse
.
setHeader
(
"Access-Control-Max-Age"
,
"3600"
);
httpResponse
.
setCharacterEncoding
(
"UTF-8"
);
httpResponse
.
setContentType
(
"application/json; charset=utf-8"
);
String
resMethods
=
httpRequest
.
getMethod
();
if
(
"OPTIONS"
.
equals
(
resMethods
))
{
Map
<
String
,
Object
>
map
=
new
HashMap
<
String
,
Object
>();
map
.
put
(
"data"
,
null
);
map
.
put
(
"code"
,
"200"
);
map
.
put
(
"msg"
,
null
);
log
.
info
(
JSONObject
.
toJSONString
(
map
,
SerializerFeature
.
WriteMapNullValue
));
httpResponse
.
getWriter
().
write
(
JSONObject
.
toJSONString
(
map
,
SerializerFeature
.
WriteMapNullValue
));
return
;
}
// String requestURL = httpRequest.getRequestURI();
// if (this.isExclusion(requestURL)) {
// chain.doFilter(httpRequest,httpResponse);
// }else {
// String userId = null;
// Claims claims = JwtUtil.checkJWT(token);
// if (claims != null) {
// userId = (String) claims.get("userId");
// } else {
// PrintWriter out = httpResponse.getWriter();
// JSONObject res = new JSONObject();
// res.put("msg", ResultCode.E9998.msg());
// res.put("code", ResultCode.E9998.val());
// res.put("data",null);
// out.append(res.toString());
// out.flush();
// return;
// }
// String tokenSystem = (String) claims.get("system");
// String tokenBrowserName = (String) claims.get("browserName");
// if(!system.equals(tokenSystem)|| !browserName.equals(tokenBrowserName)) {
// PrintWriter out = httpResponse.getWriter();
// JSONObject res = new JSONObject();
// res.put("msg", ResultCode.E9998.msg());
// res.put("code", ResultCode.E9998.val());
// res.put("data",null);
// out.append(res.toString());
// out.flush();
// return;
// }
// if (userId==null){
// PrintWriter out = httpResponse.getWriter();
// JSONObject res = new JSONObject();
// res.put("msg", ResultCode.E9998.msg());
// res.put("code", ResultCode.E9998.val());
// res.put("data",null);
// out.append(res.toString());
// out.flush();
// return;
// }else {
// String access_token = cacheService.getValue("access_token"+userId);
// if(StringUtils.isBlank(access_token)|| !token.equals(access_token)) {
// PrintWriter out = httpResponse.getWriter();
// JSONObject res = new JSONObject();
// res.put("msg", ResultCode.E9998.msg());
// res.put("code", ResultCode.E9998.val());
// res.put("data",null);
// out.append(res.toString());
// out.flush();
// return;
// }
// cacheService.expire("access_token"+userId, Constants.ACCESS_EXPIRE, java.util.concurrent.TimeUnit.SECONDS);
// List<String> menu = systemMenuService.getMenuHrefListForLoginUser(Integer.parseInt(userId));
// if(!menu.contains(requestURL)) {
// PrintWriter out = httpResponse.getWriter();
// JSONObject res = new JSONObject();
// res.put("msg", ResultCode.INVALID_AUTHCODE.msg());
// res.put("code", ResultCode.INVALID_AUTHCODE.val());
// res.put("data",null);
// out.append(res.toString());
// out.flush();
// return;
// }
// chain.doFilter(httpRequest,httpResponse);
// }
// }
chain
.
doFilter
(
httpRequest
,
httpResponse
);
}
@Override
public
void
destroy
()
{
}
public
boolean
isExclusion
(
String
requestURI
)
{
if
(
this
.
excludesPattern
==
null
)
{
return
false
;
}
else
{
if
(
this
.
contextPath
!=
null
&&
requestURI
.
startsWith
(
this
.
contextPath
))
{
requestURI
=
requestURI
.
substring
(
this
.
contextPath
.
length
());
if
(!
requestURI
.
startsWith
(
"/"
))
{
requestURI
=
"/"
+
requestURI
;
}
}
Iterator
i
$
=
this
.
excludesPattern
.
iterator
();
String
pattern
;
do
{
if
(!
i
$
.
hasNext
())
{
return
false
;
}
pattern
=
(
String
)
i
$
.
next
();
}
while
(!
this
.
pathMatcher
.
matches
(
pattern
,
requestURI
));
return
true
;
}
}
}
src/main/java/com/jz/common/jwt/JwtUserInfo.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
jwt
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
import
java.io.Serializable
;
/**
* jwt 存储的 内容
* eleven
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
JwtUserInfo
implements
Serializable
{
/**
*
*/
private
static
final
long
serialVersionUID
=
406413522260899460L
;
/**
* 账号id
*/
private
String
userId
;
/**
* 登录账号
*/
private
String
loginName
;
/**
* 姓名
*/
private
String
userName
;
private
String
system
;
private
String
browserName
;
private
String
isPassword
;
}
src/main/java/com/jz/common/jwt/JwtUtil.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
jwt
;
import
java.util.Date
;
import
org.apache.commons.lang3.StringUtils
;
import
com.jz.common.constant.Constants
;
import
io.jsonwebtoken.Claims
;
import
io.jsonwebtoken.Jwts
;
import
io.jsonwebtoken.SignatureAlgorithm
;
import
lombok.extern.slf4j.Slf4j
;
/**
* Secure工具类
*/
@Slf4j
public
class
JwtUtil
{
/**
* 过期时间,5分钟
*/
/**
* 秘钥
*/
public
static
final
String
APPSECRET
=
"9ZzhijiekeySyrTegfae2NItSfk"
;
/**
* 生成jwt
*
* @param userInfo
* @return
*/
public
static
String
geneJsonWebToken
(
JwtUserInfo
userInfo
)
{
long
nowMillis
=
System
.
currentTimeMillis
();
long
expMillis
=
nowMillis
+
Constants
.
ACCESS_EXPIRE
;
Date
exp
=
new
Date
(
expMillis
);
if
(
userInfo
==
null
||
StringUtils
.
isEmpty
(
userInfo
.
getUserId
()))
{
return
null
;
}
String
token
=
Jwts
.
builder
().
setSubject
(
userInfo
.
getUserId
())
.
claim
(
"userId"
,
userInfo
.
getUserId
())
.
claim
(
"userName"
,
userInfo
.
getUserName
())
.
claim
(
"loginName"
,
userInfo
.
getLoginName
())
.
claim
(
"system"
,
userInfo
.
getSystem
())
.
claim
(
"browserName"
,
userInfo
.
getBrowserName
())
.
claim
(
"isPassword"
,
userInfo
.
getIsPassword
())
.
setIssuedAt
(
new
Date
())
// .setExpiration(exp)
.
signWith
(
SignatureAlgorithm
.
HS256
,
APPSECRET
).
compact
();
return
token
;
}
public
static
String
geneJsonWebRefreshToken
(
JwtUserInfo
userInfo
)
{
long
nowMillis
=
System
.
currentTimeMillis
();
long
expMillis
=
nowMillis
+
Constants
.
REFRESH_EXPIRE
;
Date
exp
=
new
Date
(
expMillis
);
if
(
userInfo
==
null
||
StringUtils
.
isEmpty
(
userInfo
.
getUserId
()))
{
return
null
;
}
String
token
=
Jwts
.
builder
().
setSubject
(
userInfo
.
getUserId
())
.
claim
(
"userId"
,
userInfo
.
getUserId
())
.
claim
(
"userName"
,
userInfo
.
getUserName
())
.
claim
(
"loginName"
,
userInfo
.
getLoginName
())
.
setIssuedAt
(
new
Date
())
.
setExpiration
(
exp
)
.
signWith
(
SignatureAlgorithm
.
HS256
,
APPSECRET
).
compact
();
return
token
;
}
/**
* 校验token
*
* @param token
* @return
*/
public
static
Claims
checkJWT
(
String
token
)
{
try
{
final
Claims
claims
=
Jwts
.
parser
().
setSigningKey
(
APPSECRET
).
parseClaimsJws
(
token
).
getBody
();
return
claims
;
}
catch
(
Exception
e
)
{
}
return
null
;
}
/**
*
* @Title: getUserIdByToken
* @Description: TODO(获取userId)
* @最后修改人: niulichang-eleven
* @最后修改时间: 2020年6月11日 上午11:33:53
* @param token
* @return 对方法的参数进行描述
* @return: String 返回类型
* @throws
*/
public
static
String
getUserIdByToken
(
String
token
)
{
String
userId
=
null
;
Claims
claims
=
JwtUtil
.
checkJWT
(
token
);
if
(
claims
!=
null
)
{
userId
=
(
String
)
claims
.
get
(
"userId"
);
}
return
userId
;
}
/**
*
* @Title: getLoginNameByToken
* @Description: TODO(获取登录名称)
* @最后修改人: niulichang-eleven
* @最后修改时间: 2020年6月11日 上午11:34:09
* @param token
* @return 对方法的参数进行描述
* @return: String 返回类型
* @throws
*/
public
static
String
getLoginNameByToken
(
String
token
)
{
String
loginName
=
null
;
Claims
claims
=
JwtUtil
.
checkJWT
(
token
);
if
(
claims
!=
null
)
{
loginName
=
(
String
)
claims
.
get
(
"loginName"
);
}
else
{
try
{
throw
new
Exception
(
"非法token"
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
return
loginName
;
}
/**
*
* @Title: getUserNameByToken
* @Description: TODO(获取用户名称)
* @最后修改人: niulichang-eleven
* @最后修改时间: 2020年6月11日 上午11:34:58
* @param token
* @return 对方法的参数进行描述
* @return: String 返回类型
* @throws
*/
public
static
String
getUserNameByToken
(
String
token
)
{
String
userName
=
null
;
Claims
claims
=
JwtUtil
.
checkJWT
(
token
);
if
(
claims
!=
null
)
{
userName
=
(
String
)
claims
.
get
(
"userName"
);
}
else
{
try
{
throw
new
Exception
(
"非法token"
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
return
userName
;
}
public
static
String
getIsPasswordByToken
(
String
token
)
{
String
isPassword
=
null
;
Claims
claims
=
JwtUtil
.
checkJWT
(
token
);
if
(
claims
!=
null
)
{
isPassword
=
(
String
)
claims
.
get
(
"isPassword"
);
}
else
{
try
{
throw
new
Exception
(
"非法token"
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
return
isPassword
;
}
}
src/main/java/com/jz/common/service/PatternMatcher.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
service
;
public
interface
PatternMatcher
{
boolean
matches
(
String
var1
,
String
var2
);
}
src/main/java/com/jz/common/service/ServletPathMatcher.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
service
;
public
class
ServletPathMatcher
implements
PatternMatcher
{
private
static
final
ServletPathMatcher
INSTANCE
=
new
ServletPathMatcher
();
public
ServletPathMatcher
()
{
}
public
static
ServletPathMatcher
getInstance
()
{
return
INSTANCE
;
}
public
boolean
matches
(
String
pattern
,
String
source
)
{
if
(
pattern
!=
null
&&
source
!=
null
)
{
pattern
=
pattern
.
trim
();
source
=
source
.
trim
();
int
start
;
if
(
pattern
.
endsWith
(
"*"
))
{
start
=
pattern
.
length
()
-
2
;
if
(
source
.
length
()
>=
start
&&
pattern
.
substring
(
0
,
start
).
equals
(
source
.
substring
(
0
,
start
)))
{
return
true
;
}
}
else
if
(
pattern
.
startsWith
(
"*"
))
{
start
=
pattern
.
length
()
-
1
;
if
(
source
.
length
()
>=
start
&&
source
.
endsWith
(
pattern
.
substring
(
1
)))
{
return
true
;
}
}
else
if
(
pattern
.
contains
(
"*"
))
{
start
=
pattern
.
indexOf
(
"*"
);
int
end
=
pattern
.
lastIndexOf
(
"*"
);
if
(
source
.
startsWith
(
pattern
.
substring
(
0
,
start
))
&&
source
.
endsWith
(
pattern
.
substring
(
end
+
1
)))
{
return
true
;
}
}
else
if
(
pattern
.
equals
(
source
))
{
return
true
;
}
return
false
;
}
else
{
return
false
;
}
}
}
src/main/java/com/jz/common/utils/DateUtils.java
0 → 100644
View file @
7d574b89
This diff is collapsed.
Click to expand it.
src/main/java/com/jz/common/utils/IpUtil.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
utils
;
import
java.io.BufferedReader
;
import
java.io.IOException
;
import
java.io.InputStreamReader
;
import
java.io.LineNumberReader
;
import
java.net.InetAddress
;
import
java.net.InterfaceAddress
;
import
java.net.NetworkInterface
;
import
java.net.SocketException
;
import
java.net.UnknownHostException
;
import
java.util.ArrayList
;
import
java.util.List
;
import
java.util.stream.Collectors
;
import
javax.servlet.http.HttpServletRequest
;
public
class
IpUtil
{
/**
* 获取登录用户IP地址
*
* @param request
* @return
*/
public
static
String
getIpAddr
(
HttpServletRequest
request
)
{
String
ip
=
request
.
getHeader
(
"x-forwarded-for"
);
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getHeader
(
"Proxy-Client-IP"
);
}
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getHeader
(
"WL-Proxy-Client-IP"
);
}
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getRemoteAddr
();
}
if
(
ip
.
equals
(
"0:0:0:0:0:0:0:1"
))
{
ip
=
"本地"
;
}
return
ip
;
}
public
static
String
getIpAddrzhijie
(
HttpServletRequest
request
)
{
String
ip
=
request
.
getHeader
(
"X-Real-IP"
);
if
(
ip
!=
null
&&
!
""
.
equals
(
ip
)
&&
!
"unknown"
.
equalsIgnoreCase
(
ip
))
{
return
ip
;
}
ip
=
request
.
getHeader
(
"X-Forwarded-For"
);
if
(
ip
!=
null
&&
!
""
.
equals
(
ip
)
&&
!
"unknown"
.
equalsIgnoreCase
(
ip
))
{
// 多次反向代理后会有多个IP值,第一个为真实IP。
int
index
=
ip
.
indexOf
(
','
);
if
(
index
!=
-
1
)
{
return
ip
.
substring
(
0
,
index
);
}
else
{
return
ip
;
}
}
else
{
return
request
.
getRemoteAddr
();
}
}
public
static
String
getMACAddress
(
String
ip
){
String
str
=
""
;
String
macAddress
=
""
;
try
{
Process
p
=
Runtime
.
getRuntime
().
exec
(
"nbtstat -A "
+
ip
);
InputStreamReader
ir
=
new
InputStreamReader
(
p
.
getInputStream
());
LineNumberReader
input
=
new
LineNumberReader
(
ir
);
for
(
int
i
=
1
;
i
<
100
;
i
++)
{
str
=
input
.
readLine
();
System
.
out
.
println
(
str
);
if
(
str
!=
null
)
{
if
(
str
.
indexOf
(
"MAC Address"
)
>
1
)
{
macAddress
=
str
.
substring
(
str
.
indexOf
(
"MAC Address"
)
+
14
,
str
.
length
());
break
;
}
}
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
(
System
.
out
);
}
return
macAddress
;
}
/**
* 根据IP地址获取mac地址
*
* @param ipAddress
* 127.0.0.1
* @return
* @throws SocketException
* @throws UnknownHostException
*/
public
static
String
getLocalMac
(
String
ipAddress
)
throws
SocketException
,
UnknownHostException
{
// TODO Auto-generated method stub
String
str
=
""
;
String
macAddress
=
""
;
final
String
LOOPBACK_ADDRESS
=
"127.0.0.1"
;
// 如果为127.0.0.1,则获取本地MAC地址。
if
(
LOOPBACK_ADDRESS
.
equals
(
ipAddress
))
{
InetAddress
inetAddress
=
InetAddress
.
getLocalHost
();
// 貌似此方法需要JDK1.6。
byte
[]
mac
=
NetworkInterface
.
getByInetAddress
(
inetAddress
)
.
getHardwareAddress
();
// 下面代码是把mac地址拼装成String
StringBuilder
sb
=
new
StringBuilder
();
for
(
int
i
=
0
;
i
<
mac
.
length
;
i
++)
{
if
(
i
!=
0
)
{
sb
.
append
(
"-"
);
}
// mac[i] & 0xFF 是为了把byte转化为正整数
String
s
=
Integer
.
toHexString
(
mac
[
i
]
&
0xFF
);
sb
.
append
(
s
.
length
()
==
1
?
0
+
s
:
s
);
}
// 把字符串所有小写字母改为大写成为正规的mac地址并返回
macAddress
=
sb
.
toString
().
trim
().
toUpperCase
();
return
macAddress
;
}
else
{
// 获取非本地IP的MAC地址
try
{
System
.
out
.
println
(
ipAddress
);
Process
p
=
Runtime
.
getRuntime
().
exec
(
"nbtstat -A "
+
ipAddress
);
System
.
out
.
println
(
"===process=="
+
p
);
InputStreamReader
ir
=
new
InputStreamReader
(
p
.
getInputStream
());
BufferedReader
br
=
new
BufferedReader
(
ir
);
System
.
out
.
println
(
br
.
toString
());
while
((
str
=
br
.
readLine
())
!=
null
)
{
if
(
str
.
indexOf
(
"MAC"
)
>
1
)
{
macAddress
=
str
.
substring
(
str
.
indexOf
(
"MAC"
)
+
9
,
str
.
length
());
macAddress
=
macAddress
.
trim
();
System
.
out
.
println
(
"macAddress:"
+
macAddress
);
break
;
}
}
p
.
destroy
();
br
.
close
();
ir
.
close
();
}
catch
(
IOException
ex
)
{
}
return
macAddress
;
}
}
public
static
List
<
String
>
getMacList
()
throws
Exception
{
java
.
util
.
Enumeration
<
NetworkInterface
>
en
=
NetworkInterface
.
getNetworkInterfaces
();
StringBuilder
sb
=
new
StringBuilder
();
ArrayList
<
String
>
tmpMacList
=
new
ArrayList
<>();
while
(
en
.
hasMoreElements
())
{
NetworkInterface
iface
=
en
.
nextElement
();
List
<
InterfaceAddress
>
addrs
=
iface
.
getInterfaceAddresses
();
for
(
InterfaceAddress
addr
:
addrs
)
{
InetAddress
ip
=
addr
.
getAddress
();
NetworkInterface
network
=
NetworkInterface
.
getByInetAddress
(
ip
);
if
(
network
==
null
)
{
continue
;
}
byte
[]
mac
=
network
.
getHardwareAddress
();
if
(
mac
==
null
)
{
continue
;
}
sb
.
delete
(
0
,
sb
.
length
());
for
(
int
i
=
0
;
i
<
mac
.
length
;
i
++)
{
sb
.
append
(
String
.
format
(
"%02X%s"
,
mac
[
i
],
(
i
<
mac
.
length
-
1
)
?
"-"
:
""
));
}
tmpMacList
.
add
(
sb
.
toString
());
}
}
if
(
tmpMacList
.
size
()
<=
0
)
{
return
tmpMacList
;
}
/*** 去重,别忘了同一个网卡的ipv4,ipv6得到的mac都是一样的,肯定有重复,下面这段代码是。。流式处理 ***/
List
<
String
>
unique
=
tmpMacList
.
stream
().
distinct
().
collect
(
Collectors
.
toList
());
return
unique
;
}
public
static
String
what
(
String
ip
)
throws
SocketException
,
UnknownHostException
{
NetworkInterface
ne
=
NetworkInterface
.
getByInetAddress
(
InetAddress
.
getByName
(
ip
));
byte
[]
mac
=
ne
.
getHardwareAddress
();
StringBuffer
sb
=
new
StringBuffer
(
""
);
for
(
int
i
=
0
;
i
<
mac
.
length
;
i
++)
{
if
(
i
!=
0
)
{
sb
.
append
(
"-"
);
}
//字节转换为整数
int
temp
=
mac
[
i
]&
0xff
;
String
str
=
Integer
.
toHexString
(
temp
);
System
.
out
.
println
(
"每8位:"
+
str
);
if
(
str
.
length
()==
1
)
{
sb
.
append
(
"0"
+
str
);
}
else
{
sb
.
append
(
str
);
}
}
return
sb
.
toString
().
toUpperCase
();
}
public
static
void
main
(
String
[]
args
)
throws
Exception
{
System
.
out
.
println
(
getMACAddress
(
"192.168.31.50"
));
}
}
src/main/java/com/jz/common/utils/MD5SignUtils.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
utils
;
import
org.apache.commons.codec.digest.DigestUtils
;
import
java.io.UnsupportedEncodingException
;
/**
*
* @ClassName: MD5SignUtils
* @Description: TODO(data + 混淆串,用MD5算法签名)
* @author: niulichang
* @date: 2020年6月12日 下午2:39:51
* @最后修改人: niulichang
* @最后修改时间: 2020年6月12日 下午2:39:51
*/
public
class
MD5SignUtils
{
private
static
final
String
DEFAULT_CHARSET
=
"UTF-8"
;
/**
* 签名
*
* @PARAM SRCSTR
* @PARAM SALT 作为MD5混淆
* @RETURN
*/
public
static
String
sign
(
String
srcStr
)
throws
UnsupportedEncodingException
{
return
sign
(
srcStr
,
DEFAULT_CHARSET
);
}
/**
* 签名
*
* @param srcStr
* @param salt 作为MD5混淆
* @return
*/
public
static
String
sign
(
String
srcStr
,
String
charset
)
throws
UnsupportedEncodingException
{
return
DigestUtils
.
md5Hex
(
getContentBytes
(
srcStr
,
charset
));
}
/**
* 签名字符串
* @param text 需要签名的字符串
* @param sign 签名结果
* @param salt 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public
static
boolean
verify
(
String
text
,
String
sign
,
String
input_charset
)
{
String
mysign
=
DigestUtils
.
md5Hex
(
getContentBytes
(
text
,
input_charset
));
if
(
mysign
.
equals
(
sign
))
{
return
true
;
}
else
{
return
false
;
}
}
/**
* @param content
* @param charset
* @return
* @throws UnsupportedEncodingException
*/
private
static
byte
[]
getContentBytes
(
String
content
,
String
charset
)
{
if
(
charset
==
null
||
""
.
equals
(
charset
))
{
return
content
.
getBytes
();
}
try
{
return
content
.
getBytes
(
charset
);
}
catch
(
UnsupportedEncodingException
e
)
{
throw
new
RuntimeException
(
"MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:"
+
charset
);
}
}
}
src/main/java/com/jz/common/utils/PasswordUtil.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
utils
;
import
java.security.MessageDigest
;
import
java.util.Random
;
import
org.apache.commons.codec.binary.Hex
;
/**
* MD5加盐加密
*/
public
class
PasswordUtil
{
/**
* 生成含有随机盐的密码
*/
public
static
String
generate
(
String
password
)
{
Random
r
=
new
Random
();
StringBuilder
sb
=
new
StringBuilder
(
16
);
sb
.
append
(
r
.
nextInt
(
99999999
)).
append
(
r
.
nextInt
(
99999999
));
int
len
=
sb
.
length
();
if
(
len
<
16
)
{
for
(
int
i
=
0
;
i
<
16
-
len
;
i
++)
{
sb
.
append
(
"0"
);
}
}
String
salt
=
sb
.
toString
();
password
=
md5Hex
(
password
+
salt
);
char
[]
cs
=
new
char
[
48
];
for
(
int
i
=
0
;
i
<
48
;
i
+=
3
)
{
cs
[
i
]
=
password
.
charAt
(
i
/
3
*
2
);
char
c
=
salt
.
charAt
(
i
/
3
);
cs
[
i
+
1
]
=
c
;
cs
[
i
+
2
]
=
password
.
charAt
(
i
/
3
*
2
+
1
);
}
return
new
String
(
cs
);
}
/**
* 生成含有随机盐的密码
*/
public
static
String
generateMd5
(
String
password
,
String
salt
)
{
password
=
md5Hex
(
password
+
salt
);
// char[] cs = new char[48];
// for (int i = 0; i < 48; i += 3) {
// cs[i] = password.charAt(i / 3 * 2);
// char c = salt.charAt(i / 3);
// cs[i + 1] = c;
// cs[i + 2] = password.charAt(i / 3 * 2 + 1);
// }
return
password
;
}
/**
* 校验密码是否正确
*/
public
static
boolean
verify
(
String
password
,
String
md5
)
{
char
[]
cs1
=
new
char
[
32
];
char
[]
cs2
=
new
char
[
16
];
for
(
int
i
=
0
;
i
<
48
;
i
+=
3
)
{
cs1
[
i
/
3
*
2
]
=
md5
.
charAt
(
i
);
cs1
[
i
/
3
*
2
+
1
]
=
md5
.
charAt
(
i
+
2
);
cs2
[
i
/
3
]
=
md5
.
charAt
(
i
+
1
);
}
String
salt
=
new
String
(
cs2
);
// System.out.println("取出盐值" + salt);
return
md5Hex
(
password
+
salt
).
equals
(
new
String
(
cs1
));
}
/**
* 获取十六进制字符串形式的MD5摘要
*/
public
static
String
md5Hex
(
String
src
)
{
try
{
MessageDigest
md5
=
MessageDigest
.
getInstance
(
"MD5"
);
byte
[]
bs
=
md5
.
digest
(
src
.
getBytes
());
return
new
String
(
new
Hex
().
encode
(
bs
));
}
catch
(
Exception
e
)
{
return
null
;
}
}
public
static
void
main
(
String
[]
args
)
{
// 27756851e315a3f124a6505b795177b0d664d1d64dd3da0c
// System.out.println(verify("123456","409c2a69a24ed6db30e25a3ba56993103a8966657842ad2a"));
//
// String pwd1=generateMd5("123456","admin");
// String pwd2= generate(pwd1);
// System.out.println("pwa1===="+pwd1);
// System.out.println("pwa2===="+pwd2);
// System.out.println(verify(pwd1, pwd2));
String
password1
=
generate
(
"111111"
);
//a1ee17a8d73db50f99b72a5249b86bc2f10cc3105324b28e
System
.
out
.
println
(
"结果:"
+
password1
+
"验证"
+
verify
(
"111111"
,
password1
));
// 加密+加盐
}
}
\ No newline at end of file
src/main/java/com/jz/common/utils/RSAUtils.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
utils
;
import
org.apache.commons.codec.binary.Base64
;
import
javax.crypto.Cipher
;
import
java.security.*
;
import
java.security.spec.PKCS8EncodedKeySpec
;
import
java.security.spec.X509EncodedKeySpec
;
import
java.util.HashMap
;
import
java.util.Map
;
/**
* RSA 工具类。提供加密,解密,生成密钥对等方法。
* 需要到http://www.bouncycastle.org下载bcprov-jdk14-123.jar。
*
*/
public
class
RSAUtils
{
public
static
final
String
KEY_ALGORITHM
=
"RSA"
;
public
static
final
String
SIGNATURE_ALGORITHM
=
"MD5withRSA"
;
private
static
final
String
PUBLIC_KEY
=
"RSAPublicKey"
;
private
static
final
String
PRIVATE_KEY
=
"RSAPrivateKey"
;
public
static
byte
[]
decryptBASE64
(
String
key
)
{
return
Base64
.
decodeBase64
(
key
);
}
public
static
String
encryptBASE64
(
byte
[]
bytes
)
{
return
Base64
.
encodeBase64String
(
bytes
);
}
/**
* 用私钥对信息生成数字签名
*
* @param data 加密数据
* @param privateKey 私钥
* @return
* @throws Exception
*/
public
static
String
sign
(
byte
[]
data
,
String
privateKey
)
throws
Exception
{
// 解密由base64编码的私钥
byte
[]
keyBytes
=
decryptBASE64
(
privateKey
);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec
pkcs8KeySpec
=
new
PKCS8EncodedKeySpec
(
keyBytes
);
// KEY_ALGORITHM 指定的加密算法
KeyFactory
keyFactory
=
KeyFactory
.
getInstance
(
KEY_ALGORITHM
);
// 取私钥匙对象
PrivateKey
priKey
=
keyFactory
.
generatePrivate
(
pkcs8KeySpec
);
// 用私钥对信息生成数字签名
Signature
signature
=
Signature
.
getInstance
(
SIGNATURE_ALGORITHM
);
signature
.
initSign
(
priKey
);
signature
.
update
(
data
);
return
encryptBASE64
(
signature
.
sign
());
}
/**
* 校验数字签名
*
* @param data 加密数据
* @param publicKey 公钥
* @param sign 数字签名
* @return 校验成功返回true 失败返回false
* @throws Exception
*/
public
static
boolean
verify
(
byte
[]
data
,
String
publicKey
,
String
sign
)
throws
Exception
{
// 解密由base64编码的公钥
byte
[]
keyBytes
=
decryptBASE64
(
publicKey
);
// 构造X509EncodedKeySpec对象
X509EncodedKeySpec
keySpec
=
new
X509EncodedKeySpec
(
keyBytes
);
// KEY_ALGORITHM 指定的加密算法
KeyFactory
keyFactory
=
KeyFactory
.
getInstance
(
KEY_ALGORITHM
);
// 取公钥匙对象
PublicKey
pubKey
=
keyFactory
.
generatePublic
(
keySpec
);
Signature
signature
=
Signature
.
getInstance
(
SIGNATURE_ALGORITHM
);
signature
.
initVerify
(
pubKey
);
signature
.
update
(
data
);
// 验证签名是否正常
return
signature
.
verify
(
decryptBASE64
(
sign
));
}
public
static
byte
[]
decryptByPrivateKey
(
byte
[]
data
,
String
key
)
throws
Exception
{
// 对密钥解密
byte
[]
keyBytes
=
decryptBASE64
(
key
);
// 取得私钥
PKCS8EncodedKeySpec
pkcs8KeySpec
=
new
PKCS8EncodedKeySpec
(
keyBytes
);
KeyFactory
keyFactory
=
KeyFactory
.
getInstance
(
KEY_ALGORITHM
);
Key
privateKey
=
keyFactory
.
generatePrivate
(
pkcs8KeySpec
);
// 对数据解密
Cipher
cipher
=
Cipher
.
getInstance
(
keyFactory
.
getAlgorithm
());
cipher
.
init
(
Cipher
.
DECRYPT_MODE
,
privateKey
);
return
cipher
.
doFinal
(
data
);
}
/**
* 解密<br>
* 用私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public
static
byte
[]
decryptByPrivateKey
(
String
data
,
String
key
)
{
try
{
return
decryptByPrivateKey
(
decryptBASE64
(
data
),
key
);
}
catch
(
Exception
e
)
{
}
return
null
;
}
/**
* 解密<br>
* 用公钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public
static
byte
[]
decryptByPublicKey
(
byte
[]
data
,
String
key
)
throws
Exception
{
// 对密钥解密
byte
[]
keyBytes
=
decryptBASE64
(
key
);
// 取得公钥
X509EncodedKeySpec
x509KeySpec
=
new
X509EncodedKeySpec
(
keyBytes
);
KeyFactory
keyFactory
=
KeyFactory
.
getInstance
(
KEY_ALGORITHM
);
Key
publicKey
=
keyFactory
.
generatePublic
(
x509KeySpec
);
// 对数据解密
Cipher
cipher
=
Cipher
.
getInstance
(
keyFactory
.
getAlgorithm
());
cipher
.
init
(
Cipher
.
DECRYPT_MODE
,
publicKey
);
return
cipher
.
doFinal
(
data
);
}
/**
* 加密<br>
* 用公钥加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public
static
byte
[]
encryptByPublicKey
(
String
data
,
String
key
)
throws
Exception
{
// 对公钥解密
byte
[]
keyBytes
=
decryptBASE64
(
key
);
// 取得公钥
X509EncodedKeySpec
x509KeySpec
=
new
X509EncodedKeySpec
(
keyBytes
);
KeyFactory
keyFactory
=
KeyFactory
.
getInstance
(
KEY_ALGORITHM
);
Key
publicKey
=
keyFactory
.
generatePublic
(
x509KeySpec
);
// 对数据加密
Cipher
cipher
=
Cipher
.
getInstance
(
keyFactory
.
getAlgorithm
());
cipher
.
init
(
Cipher
.
ENCRYPT_MODE
,
publicKey
);
return
cipher
.
doFinal
(
data
.
getBytes
());
}
/**
* 加密<br>
* 用私钥加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public
static
byte
[]
encryptByPrivateKey
(
byte
[]
data
,
String
key
)
throws
Exception
{
// 对密钥解密
byte
[]
keyBytes
=
decryptBASE64
(
key
);
// 取得私钥
PKCS8EncodedKeySpec
pkcs8KeySpec
=
new
PKCS8EncodedKeySpec
(
keyBytes
);
KeyFactory
keyFactory
=
KeyFactory
.
getInstance
(
KEY_ALGORITHM
);
Key
privateKey
=
keyFactory
.
generatePrivate
(
pkcs8KeySpec
);
// 对数据加密
Cipher
cipher
=
Cipher
.
getInstance
(
keyFactory
.
getAlgorithm
());
cipher
.
init
(
Cipher
.
ENCRYPT_MODE
,
privateKey
);
return
cipher
.
doFinal
(
data
);
}
/**
* 取得私钥
*
* @param keyMap
* @return
* @throws Exception
*/
public
static
String
getPrivateKey
(
Map
<
String
,
Key
>
keyMap
)
throws
Exception
{
Key
key
=
(
Key
)
keyMap
.
get
(
PRIVATE_KEY
);
return
encryptBASE64
(
key
.
getEncoded
());
}
/**
* 取得公钥
*
* @param keyMap
* @return
* @throws Exception
*/
public
static
String
getPublicKey
(
Map
<
String
,
Key
>
keyMap
)
throws
Exception
{
Key
key
=
keyMap
.
get
(
PUBLIC_KEY
);
return
encryptBASE64
(
key
.
getEncoded
());
}
/**
* 初始化密钥
*
* @return
* @throws Exception
*/
public
static
Map
<
String
,
Key
>
initKey
()
throws
Exception
{
KeyPairGenerator
keyPairGen
=
KeyPairGenerator
.
getInstance
(
KEY_ALGORITHM
);
keyPairGen
.
initialize
(
1024
);
KeyPair
keyPair
=
keyPairGen
.
generateKeyPair
();
Map
<
String
,
Key
>
keyMap
=
new
HashMap
(
2
);
keyMap
.
put
(
PUBLIC_KEY
,
keyPair
.
getPublic
());
// 公钥
keyMap
.
put
(
PRIVATE_KEY
,
keyPair
.
getPrivate
());
// 私钥
return
keyMap
;
}
public
static
void
main
(
String
[]
args
)
throws
Exception
{
Map
<
String
,
Key
>
keyMap
=
RSAUtils
.
initKey
();
String
publicKey
=
RSAUtils
.
getPublicKey
(
keyMap
);
String
privateKey
=
RSAUtils
.
getPrivateKey
(
keyMap
);
System
.
err
.
println
(
"公钥:"
+
publicKey
);
System
.
err
.
println
(
"私钥"
+
privateKey
);
System
.
err
.
println
(
"公钥加密——私钥解密"
);
String
inputStr
=
"123456"
;
byte
[]
encodedData
=
RSAUtils
.
encryptByPublicKey
(
inputStr
,
publicKey
);
byte
[]
decodedData
=
RSAUtils
.
decryptByPrivateKey
(
encodedData
,
privateKey
);
String
outputStr
=
new
String
(
decodedData
);
System
.
err
.
println
(
"加密前: "
+
inputStr
+
"\n\r"
+
"解密后: "
+
outputStr
);
}
}
\ No newline at end of file
src/main/java/com/jz/common/utils/StringUtils.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
common
.
utils
;
import
java.util.regex.Matcher
;
import
java.util.regex.Pattern
;
public
class
StringUtils
{
/**
* <p>
* Checks if a CharSequence is whitespace, empty ("") or null.
* </p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs
* the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace
* @since 2.0
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public
static
boolean
isBlank
(
final
CharSequence
cs
)
{
int
strLen
;
if
(
cs
==
null
||
(
strLen
=
cs
.
length
())
==
0
)
{
return
true
;
}
for
(
int
i
=
0
;
i
<
strLen
;
i
++)
{
if
(
Character
.
isWhitespace
(
cs
.
charAt
(
i
))
==
false
)
{
return
false
;
}
}
return
true
;
}
public
static
boolean
isNotBlank
(
final
CharSequence
cs
)
{
return
!
isBlank
(
cs
);
}
public
static
String
nvl
(
String
sIn
)
{
return
(
sIn
==
null
||
"null"
.
equals
(
sIn
))
?
""
:
sIn
;
}
public
static
String
nvl
(
Object
sIn
)
{
return
(
sIn
==
null
||
"null"
.
equals
(
sIn
))
?
""
:
sIn
.
toString
();
}
public
static
String
nvl
(
String
sIn
,
String
defaultStr
)
{
return
(
sIn
==
null
||
"null"
.
equals
(
sIn
))
?
defaultStr
:
sIn
;
}
public
static
boolean
hasLength
(
String
str
)
{
return
(
str
!=
null
&&
str
.
length
()
>
0
);
}
public
static
boolean
isMobile
(
String
str
)
{
if
(!
hasText
(
str
))
{
return
false
;
}
Pattern
p
=
null
;
Matcher
m
=
null
;
boolean
b
=
false
;
p
=
Pattern
.
compile
(
"^[1][3,4,5,7,8][0-9]{9}$"
);
// 验证手机号
m
=
p
.
matcher
(
str
);
b
=
m
.
matches
();
return
b
;
}
public
static
boolean
hasText
(
String
str
)
{
if
(!
hasLength
(
str
))
{
return
false
;
}
int
strLen
=
str
.
length
();
for
(
int
i
=
0
;
i
<
strLen
;
i
++)
{
if
(!
Character
.
isWhitespace
(
str
.
charAt
(
i
)))
{
return
true
;
}
}
return
false
;
}
public
static
boolean
isNull
(
String
str
)
{
return
str
==
null
||
str
.
isEmpty
();
}
public
static
boolean
isNotNull
(
String
str
)
{
return
!
isNull
(
str
);
}
// Empty checks
// -----------------------------------------------------------------------
/**
* <p>
* Checks if a CharSequence is empty ("") or null.
* </p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>
* NOTE: This method changed in Lang version 2.0. It no longer trims the
* CharSequence. That functionality is available in isBlank().
* </p>
*
* @param cs
* the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public
static
boolean
isEmpty
(
final
CharSequence
cs
)
{
return
cs
==
null
||
cs
.
length
()
==
0
;
}
/** 获取对象字符值,空白字符串将返回默认值 */
public
static
String
getStringValue
(
Object
object
,
String
defaultValue
)
{
if
(
object
==
null
||
object
.
toString
().
trim
().
equals
(
""
))
{
return
defaultValue
;
}
else
{
return
object
.
toString
();
}
}
public
static
boolean
isNumeric
(
String
str
)
{
Pattern
pattern
=
Pattern
.
compile
(
"^\\d+$"
);
Matcher
isNum
=
pattern
.
matcher
(
str
);
if
(!
isNum
.
matches
())
{
return
false
;
}
return
true
;
}
public
static
String
toString
(
Object
obj
)
{
if
(
obj
==
null
)
return
""
;
return
obj
.
toString
();
}
public
static
String
toTrimString
(
String
str
)
{
return
toString
(
str
).
trim
();
}
public
static
String
toString
(
String
[]
s
)
{
if
(
s
==
null
)
return
""
;
StringBuffer
sb
=
new
StringBuffer
();
for
(
int
i
=
0
;
i
<
s
.
length
;
++
i
)
sb
.
append
(
s
[
i
]
+
((
i
<
s
.
length
-
1
)
?
","
:
""
));
return
sb
.
toString
();
}
public
static
String
byteToString
(
byte
[]
b
)
{
String
temp
=
""
;
for
(
int
i
=
0
;
i
<
b
.
length
;
++
i
)
temp
=
temp
+
new
Byte
(
b
[
i
]).
toString
()
+
";"
;
return
temp
;
}
public
static
byte
[]
stringtobyte
(
String
s
)
{
String
[]
temp
=
s
.
split
(
";"
);
byte
[]
b
=
new
byte
[
temp
.
length
];
for
(
int
i
=
0
;
i
<
temp
.
length
;
++
i
)
b
[
i
]
=
new
Byte
(
temp
[
i
]).
byteValue
();
return
b
;
}
public
static
boolean
sql_inj
(
String
str
)
{
String
inj_str
=
"'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or |-|+|,"
;
String
inj_stra
[]
=
inj_str
.
split
(
"\\|"
);
for
(
int
i
=
0
;
i
<
inj_stra
.
length
;
i
++
)
{
if
(
str
.
indexOf
(
inj_stra
[
i
])>=
0
)
{
return
true
;
}
}
return
false
;
}
}
src/main/java/com/jz/dmp/modules/controller/toolsController.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
dmp
.
modules
.
controller
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RequestMethod
;
import
com.jz.common.constant.JsonResult
;
import
com.jz.dmp.modules.service.AtomBaseCacheService
;
/**
* 暂时注释
* @author 86186
*
*/
//@RestController
//@RequestMapping("/api/tools")
public
class
toolsController
{
@Autowired
private
AtomBaseCacheService
<
String
>
cacheService
;
/**
* 删除redis 中所有key
* @return
*/
@RequestMapping
(
value
=
"/delRedisKeys"
,
method
=
RequestMethod
.
GET
)
public
JsonResult
delRedisKeys
(
String
key
)
{
System
.
out
.
println
(
"key........"
+
key
);
cacheService
.
delKyes
(
key
);
return
new
JsonResult
();
}
}
src/main/java/com/jz/dmp/modules/service/AtomBaseCacheService.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
dmp
.
modules
.
service
;
import
java.util.concurrent.TimeUnit
;
public
interface
AtomBaseCacheService
<
T
>
{
public
void
setValue
(
String
key
,
T
value
);
public
void
setValue
(
String
key
,
T
value
,
Long
time
);
public
boolean
setNEX
(
String
key
,
T
value
);
public
T
getValue
(
String
key
);
public
T
remove
(
String
key
);
public
Boolean
expire
(
String
key
,
final
long
timeout
,
final
TimeUnit
unit
);
public
void
delKyes
(
String
key
)
;
}
src/main/java/com/jz/dmp/modules/service/impl/AtomBaseCacheServiceImpl.java
0 → 100644
View file @
7d574b89
package
com
.
jz
.
dmp
.
modules
.
service
.
impl
;
import
java.util.Set
;
import
java.util.concurrent.TimeUnit
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.data.redis.core.RedisTemplate
;
import
org.springframework.stereotype.Service
;
import
com.jz.dmp.modules.service.AtomBaseCacheService
;
@Service
public
class
AtomBaseCacheServiceImpl
<
T
>
implements
AtomBaseCacheService
<
T
>
{
@Autowired
private
RedisTemplate
<
String
,
T
>
redisTemplate
;
@Override
public
void
setValue
(
String
key
,
T
value
)
{
redisTemplate
.
opsForValue
().
set
(
key
,
value
);
}
@Override
public
T
getValue
(
String
key
)
{
return
redisTemplate
.
opsForValue
().
get
(
key
);
}
@Override
public
void
setValue
(
String
key
,
T
value
,
Long
time
)
{
redisTemplate
.
opsForValue
().
set
(
key
,
value
,
time
,
TimeUnit
.
SECONDS
);
}
@Override
public
boolean
setNEX
(
String
key
,
T
value
)
{
return
redisTemplate
.
opsForValue
().
setIfAbsent
(
key
,
value
);
}
@Override
public
T
remove
(
String
key
)
{
T
value
=
redisTemplate
.
opsForValue
().
get
(
key
);
redisTemplate
.
delete
(
key
);
return
value
;
}
@Override
public
Boolean
expire
(
String
key
,
long
timeout
,
TimeUnit
unit
)
{
return
redisTemplate
.
expire
(
key
,
timeout
,
java
.
util
.
concurrent
.
TimeUnit
.
SECONDS
);
}
@Override
public
void
delKyes
(
String
key
)
{
Set
<
String
>
keys
=
redisTemplate
.
keys
(
key
+
"*"
);
redisTemplate
.
delete
(
keys
);
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment