Commit 02be8110 authored by kang.nie@inzymeits.com's avatar kang.nie@inzymeits.com
Browse files

初始化代码

parent e9f88257
Pipeline #3111 failed with stages
in 0 seconds
package com.cusc.nirvana.user.ciam.dao.handler;
import com.cusc.nirvana.user.util.crypt.CryptKeyUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 拦截 JavaType 为 #{@link EncryptData} 的 SQL
* <p>
* 注意:
* </p>
* <p>
* 1. 加密时字段只过滤 null值,明文不做任何处理直接加密
* </p>
* <p>
* 2. fail fast 模式,当加/解密失败时,立即抛出异常
* </p>
*
* @author xufeng @ 2017年8月31日
*/
@MappedTypes(EncryptData.class)
public class EncryptDataTypeHandler extends BaseTypeHandler<String> {
private static final Logger logger = LoggerFactory.getLogger(EncryptDataTypeHandler.class);
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
throws SQLException {
ps.setString(i, CryptKeyUtil.encryptToBase64(parameter));
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
return CryptKeyUtil.decryptByBase64(rs.getString(columnName));
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return CryptKeyUtil.decryptByBase64(rs.getString(columnIndex));
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return CryptKeyUtil.decryptByBase64(cs.getString(columnIndex));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cusc.nirvana.user.ciam.dao.CiamUserDao">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.cusc.nirvana.user.ciam.dao.entity.CiamUserPO">
<id column="id" property="id"/>
<result column="uuid" property="uuid"/>
<result column="phone_num" javaType="encryptData" property="phoneNum"/>
<result column="status" property="status"/>
<result column="tenant_no" property="tenantNo"/>
<result column="routing_key" property="routingKey"/>
<result column="is_delete" property="isDelete"/>
<result column="create_time" property="createTime"/>
<result column="update_time" property="updateTime"/>
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
id
, uuid, phone_num, status, tenant_no,routing_key, is_delete, create_time, update_time
</sql>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cusc.nirvana.user.ciam.dao.UserThirdpartyDao">
<resultMap type="com.cusc.nirvana.user.ciam.dao.entity.UserThirdpartyPO" id="userThirdpartyMap">
<result property="uuid" column="uuid" />
<result property="userId" column="user_id" />
<result property="thirdPartyType" column="third_party_type" />
<result property="thirdPartyId" column="third_party_id" />
<result property="tenantNo" column="tenant_no"/>
<result property="routingKey" column="routing_key"/>
<result property="operator" column="operator" />
</resultMap>
</mapper>
package com.cusc.nirvana.user.ciam.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.cusc.nirvana.user.ciam.dao.entity.CiamUserPO;
import com.cusc.nirvana.user.ciam.dto.*;
import java.util.List;
/**
* <p>
* 终端用户 服务类
* </p>
*
* @author yuy336
* @since 2021-10-14
*/
public interface ICiamUserService extends IService<CiamUserPO> {
/**
* Description: 添加用户,存在则返回已存在的用户信息
* <br />
* CreateDate 2021-11-10 13:58:57
*
* @author yuyi
**/
CiamUserDTO addOrGet(CiamUserDTO bean);
/**
* Description: 删除用户
* <br />
* CreateDate 2021-11-10 13:58:57
*
* @author yuyi
**/
boolean delete(CiamUserDTO bean);
/**
* Description: 编辑用户
* <br />
* CreateDate 2021-11-10 13:58:57
*
* @author yuyi
**/
boolean update(CiamUserDTO entity);
/**
* Description: 查询用户集合
* <br />
* CreateDate 2021-11-10 14:04:10
*
* @author yuyi
**/
List<CiamUserDTO> query(CiamUserDTO bean);
/**
* Description: 查询单个用户
* <br />
* CreateDate 2021-11-10 14:03:49
*
* @author yuyi
**/
CiamUserDTO get(CiamUserDTO bean);
/**
* Description: 通过手机号查询用户信息
* <br />
* CreateDate 2021-11-10 14:28:51
*
* @author yuyi
**/
CiamUserDTO getUserByPhoneTenantNo(CiamUserDTO bean);
///**
// * Description: 登录
// * <br />
// * CreateDate 2022-04-14 10:07:51
// *
// * @author huzl
// **/
//LoginResponseDTO login(LoginRequestDTO loginRequestDTO);
}
package com.cusc.nirvana.user.ciam.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.cusc.nirvana.user.ciam.dao.entity.UserThirdpartyPO;
import com.cusc.nirvana.user.ciam.dto.CiamUserThirdpartyDTO;
import java.util.List;
/**
* 终端用户三方认证(UserThirdparty)表服务接口
*
* @author yuy336
* @since 2022-05-05 19:54:47
*/
public interface IUserThirdpartyService extends IService<UserThirdpartyPO> {
/**
* 通过UUID查询单条数据
*
* @param bean
* @return 实例对象
*/
CiamUserThirdpartyDTO getByUuid(CiamUserThirdpartyDTO bean);
/**
* 通过查询条件查询集合数据
*
* @param bean
* @return 集合对象
*/
List<CiamUserThirdpartyDTO> queryByList(CiamUserThirdpartyDTO bean);
/**
* 新增数据
*
* @param bean 实例对象
* @return 实例对象
*/
CiamUserThirdpartyDTO insert(CiamUserThirdpartyDTO bean);
/**
* 修改数据
*
* @param bean 实例对象
* @return 实例对象
*/
CiamUserThirdpartyDTO update(CiamUserThirdpartyDTO bean);
/**
* 通过主键删除数据
*
* @param bean
* @return 是否成功
*/
boolean deleteById(CiamUserThirdpartyDTO bean);
}
package com.cusc.nirvana.user.ciam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.user.ciam.constants.CiamConstant;
import com.cusc.nirvana.user.ciam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.ciam.constants.ResponseCode;
import com.cusc.nirvana.user.ciam.converter.UserConverter;
import com.cusc.nirvana.user.ciam.dao.CiamUserDao;
import com.cusc.nirvana.user.ciam.dao.entity.CiamUserPO;
import com.cusc.nirvana.user.ciam.dto.CiamUserDTO;
import com.cusc.nirvana.user.ciam.service.ICiamUserService;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
import com.cusc.nirvana.user.util.crypt.CryptKeyUtil;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 终端用户 服务实现类
* </p>
*
* @author yuy336
* @since 2021-10-14
*/
@Service
public class CiamUserServiceImpl extends ServiceImpl<CiamUserDao, CiamUserPO> implements ICiamUserService {
@Override
@Transactional
public CiamUserDTO addOrGet(CiamUserDTO bean) {
if (CuscStringUtils.isEmpty(bean.getPhoneNum()) || bean.getTenantNo() == null) {
return null;
}
CiamUserPO entity0;
CiamUserDTO retUser = getUserByPhoneTenantNo(bean);
if (retUser != null && CuscStringUtils.isNotEmpty(retUser.getUuid())) {
return retUser;
}
//新增用户
entity0 = UserConverter.INSTANCE.dtoDataToPo(bean);
entity0.setUuid(CuscStringUtils.generateUuid());
bean.setUuid(entity0.getUuid());
this.save(entity0);
return bean;
}
/**
* Description: 通过手机号查询用户信息
* <br />
* CreateDate 2021-11-10 14:28:51
*
* @author yuyi
**/
@Override
public CiamUserDTO getUserByPhoneTenantNo(CiamUserDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("phone_num", CryptKeyUtil.encryptToBase64(bean.getPhoneNum()));
queryWrapper.eq("tenant_no", bean.getTenantNo());
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.eq(bean.getStatus() != null, "status", bean.getStatus());
return UserConverter.INSTANCE.poDataToDto(this.getOne(queryWrapper));
}
@Override
public boolean delete(CiamUserDTO bean) {
CiamUserDTO entity0 = this.get(bean);
if (entity0 == null) {
return false;
}
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("uuid", bean.getUuid());
updateWrapper.eq("tenant_no", bean.getTenantNo());
updateWrapper.set("is_delete", CommonDeleteEnum.DELETED.getCode());
return this.update(updateWrapper);
}
@Override
public boolean update(CiamUserDTO bean) {
CiamUserPO userDO = this.getUserDO(bean);
if (userDO == null) {
return false;
}
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("uuid", bean.getUuid());
updateWrapper.eq("tenant_no", bean.getTenantNo());
updateWrapper.eq("routing_key", userDO.getRoutingKey());
updateWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
BeanUtils.copyProperties(bean, userDO);
//设置不更新字段
userDO.setUuid(null);
userDO.setTenantNo(null);
return this.update(userDO, updateWrapper);
}
@Override
public List<CiamUserDTO> query(CiamUserDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("tenant_no", bean.getTenantNo());
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
List<CiamUserPO> recordList = this.list(queryWrapper);
return transToDTOList(recordList);
}
@Override
public CiamUserDTO get(CiamUserDTO bean) {
CiamUserPO userSubjectDO = this.getUserDO(bean);
CiamUserDTO ret = new CiamUserDTO();
if (userSubjectDO != null) {
ret = UserConverter.INSTANCE.poDataToDto(userSubjectDO);
}
return ret;
}
/**
* Description: 获取用户do
* <br />
* CreateDate 2021-11-10 14:28:51
*
* @author yuyi
**/
private CiamUserPO getUserDO(CiamUserDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", bean.getUuid());
queryWrapper.eq("tenant_no", bean.getTenantNo());
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
return this.getOne(queryWrapper);
}
/**
* Description: 将DO集合转为DTO集合
* <br />
* CreateDate 2021-11-02 11:49:31
*
* @author yuyi
**/
private List<CiamUserDTO> transToDTOList(List<CiamUserPO> recordList) {
List<CiamUserDTO> retList = new ArrayList<>();
if (CollectionUtils.isEmpty(recordList)) {
return retList;
}
CiamUserDTO userDTO;
for (CiamUserPO bean : recordList) {
userDTO = new CiamUserDTO();
BeanUtils.copyProperties(bean, userDTO);
retList.add(userDTO);
}
return retList;
}
///**
// * Description: 自助注册,如果有账户就直接登录,没有账户就创建一个账户,然后登录
// * <br />
// * CreateDate 2022-04-14 11:49:31
// *
// * @author huzl
// **/
//@Override
//public LoginResponseDTO login(LoginRequestDTO loginRequestDTO) {
// MobileLoginReq req = new MobileLoginReq();
// req.setApplicationId(applicationId);
// req.setTenantNo(loginRequestDTO.getTenantNo());
// req.setPhone(loginRequestDTO.getPhone());
// req.setCaptcha(loginRequestDTO.getSms());
//
// QueryWrapper systemRoutingWrapper = new QueryWrapper();
// systemRoutingWrapper.eq("query_key", loginRequestDTO.getPhone());
// SystemRoutingPO systemRoutingDO = systemRoutingService.getOne(systemRoutingWrapper);
// //账户不存在
// if (Objects.isNull(systemRoutingDO)) {
// UserPO entity0 = createCiamUser(loginRequestDTO);
// //设置UUID
// req.setUuid(entity0.getUuid());
// //登录
// Response<Oauth2Token> response = loginClient.customerMobileLogin(req);
// //登录失败 throw exception
// if (null == response || !response.isSuccess() || null == response.getData()) {
// return null;
// }
//
// Oauth2Token data = response.getData();
// return new LoginResponseDTO().setAccessToken(data.getAccess_token())
// .setRefreshToken(data.getRefresh_token())
// .setExpiresIn(data.getExpires_in())
// .setLoginName(data.getInfo().getLoginName())
// .setNickName(data.getInfo().getNickName())
// .setUserId(data.getInfo().getUserId());
// }
//
// //查询手机号是否存在
// QueryWrapper userWrapper = new QueryWrapper();
// userWrapper.eq("phone_num", ciamCryptService.encryptData(loginRequestDTO.getPhone()));
// userWrapper.eq("routing_value", systemRoutingDO.getRoutingValue());
// userWrapper.eq("tenant_no", loginRequestDTO.getTenantNo());
// userWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
// UserPO userDO = this.getOne(userWrapper);
//
// //帐号不存在
// if (Objects.isNull(userDO)) {
// UserPO entity0 = createCiamUser(loginRequestDTO);
// //设置UUID
// req.setUuid(entity0.getUuid());
// } else {
// //设置UUID
// req.setUuid(userDO.getUuid());
// }
//
// //登录
// Response<Oauth2Token> response = loginClient.customerMobileLogin(req);
//
// //登录失败 throw exception
// if (null == response || !response.isSuccess() || null == response.getData()) {
// return null;
// }
//
// Oauth2Token data = response.getData();
// return new LoginResponseDTO().setAccessToken(data.getAccess_token())
// .setRefreshToken(data.getRefresh_token())
// .setExpiresIn(data.getExpires_in())
// .setLoginName(data.getInfo().getLoginName())
// .setNickName(data.getInfo().getNickName())
// .setUserId(data.getInfo().getUserId());
//}
}
package com.cusc.nirvana.user.ciam.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.user.ciam.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.ciam.converter.UserThirdpartyConverter;
import com.cusc.nirvana.user.ciam.dao.UserThirdpartyDao;
import com.cusc.nirvana.user.ciam.dao.entity.UserThirdpartyPO;
import com.cusc.nirvana.user.ciam.dto.CiamUserThirdpartyDTO;
import com.cusc.nirvana.user.ciam.service.IUserThirdpartyService;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 终端用户三方认证(UserThirdparty)表服务实现类
*
* @author yuy336
* @since 2022-05-05 19:54:47
*/
@Service
public class UserThirdpartyServiceImpl extends ServiceImpl<UserThirdpartyDao, UserThirdpartyPO> implements IUserThirdpartyService {
/**
* 通过UUID查询单条数据
*
* @param bean
* @return 实例对象
*/
@Override
public CiamUserThirdpartyDTO getByUuid(CiamUserThirdpartyDTO bean) {
UserThirdpartyPO record = this.getPoByUuid(bean.getUuid());;
return UserThirdpartyConverter.INSTANCE.poToDto(record);
}
/**
* 通过查询条件查询集合数据
*
* @param bean
* @return 集合对象
*/
@Override
public List<CiamUserThirdpartyDTO> queryByList(CiamUserThirdpartyDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
List<UserThirdpartyPO> record = this.list(queryWrapper);
return UserThirdpartyConverter.INSTANCE.poListToDtoList(record);
}
/**
* 新增数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public CiamUserThirdpartyDTO insert(CiamUserThirdpartyDTO bean) {
UserThirdpartyPO userThirdpartyPO = UserThirdpartyConverter.INSTANCE.dtoToPo(bean);
userThirdpartyPO.setUuid(CuscStringUtils.generateUuid());
this.save(userThirdpartyPO);
bean.setUuid(userThirdpartyPO.getUuid());
return bean;
}
/**
* 修改数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public CiamUserThirdpartyDTO update(CiamUserThirdpartyDTO bean) {
UserThirdpartyPO userThirdpartyPO = this.getPoByUuid(bean.getUuid());
if(userThirdpartyPO == null){
return null;
}
UserThirdpartyPO tmpBean = UserThirdpartyConverter.INSTANCE.dtoToPo(bean);
tmpBean.setId(userThirdpartyPO.getId());
this.updateById(tmpBean);
return bean;
}
/**
* 通过主键删除数据
* @param bean 实例对象
* @return 是否成功
*/
@Override
@Transactional
public boolean deleteById(CiamUserThirdpartyDTO bean) {
UserThirdpartyPO userThirdpartyPO = this.getPoByUuid(bean.getUuid());
if (userThirdpartyPO == null) {
return false;
}
UserThirdpartyPO tmpBean = new UserThirdpartyPO();
tmpBean.setId(userThirdpartyPO.getId());
tmpBean.setIsDelete(CommonDeleteEnum.DELETED.getCode());
return this.updateById(tmpBean);
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private UserThirdpartyPO getPoByUuid(String uuid) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
return this.getOne(queryWrapper);
}
}
package com.cusc.nirvana.user.ciam.util;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Description: 时间工具类
* <br />
* CreateDate 2021-12-08 16:42
*
* @author yuy336
**/
public class DateUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(DateUtil.class);
/**
* 比较两个日期的大小
*
* @param date1 起始日期
* @param date2 结束日期
* @return date1小于date2返回-1,date1大于date2返回1,相等返回0
*/
public static int compareDate(Date date1, Date date2) {
return date1.compareTo(date2);
}
/**
* 计算两个日期之间相差的天数
*
* @param beginDate 起始日期
* @param endDate 结束日期
* @return 相差天数
*/
public static int daysBetween(Date beginDate, Date endDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
beginDate = sdf.parse(sdf.format(beginDate));
endDate = sdf.parse(sdf.format(endDate));
long time1 = beginDate.getTime();
long time2 = endDate.getTime();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
} catch (ParseException e) {
LOGGER.error("DateUtil.daysBetween error ! ", e);
return -1;
}
}
/**
* 计算两个日期之间相差的天数
*
* @param dateStr 日期天厨
* @return 日期类型
*/
public static Date parseDate(String dateStr, String format) {
if (CuscStringUtils.isEmpty(format)) {
format = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat formatter = new SimpleDateFormat(format);
try {
return formatter.parse(dateStr);
} catch (ParseException e) {
LOGGER.error("DateUtil.parseDate error ! ", e);
return null;
}
}
}
package com.cusc.nirvana.user.ciam.util;
import com.cusc.nirvana.user.ciam.constants.ResponseCode;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
/**
* Description: 参数校验工具类
* <br />
* CreateDate 2021-11-09 17:42
*
* @author yuyi
**/
public class ParameterCheckUtil {
/**
* Description: 检查非空
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(String parameter) {
if (CuscStringUtils.isEmpty(parameter)) {
throw new CuscUserException(ResponseCode.PARAMETER_NOT_NULL.getCode() + "",
ResponseCode.PARAMETER_NOT_NULL.getMsg());
}
}
/**
* Description: 检查非空
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(String parameter, ResponseCode code) {
if (CuscStringUtils.isEmpty(parameter)) {
throw new CuscUserException(code.getCode() + "", code.getMsg());
}
}
/**
* Description: 检查非空
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(Integer parameter, ResponseCode code) {
if (parameter == null) {
throw new CuscUserException(code.getCode() + "", code.getMsg());
}
}
/**
* Description: 检查非空
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(Integer parameter) {
if (parameter == null) {
throw new CuscUserException(ResponseCode.PARAMETER_NOT_NULL.getCode() + "",
ResponseCode.PARAMETER_NOT_NULL.getMsg());
}
}
/**
* Description: 检查非空-长整型
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(Long parameter, ResponseCode code) {
if (parameter == null) {
throw new CuscUserException(code.getCode() + "", code.getMsg());
}
}
/**
* Description: 检查非空-长整型
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(Long parameter) {
if (parameter == null) {
throw new CuscUserException(ResponseCode.PARAMETER_NOT_NULL.getCode() + "",
ResponseCode.PARAMETER_NOT_NULL.getMsg());
}
}
}
package com.cusc.nirvana.user.ciam.util.cache;
import com.cusc.nirvana.user.util.CuscStringUtils;
import com.google.common.cache.Cache;
/**
* guava缓存service
*
* @author yuy336
* @create 2021-10-22 15:01
**/
public interface IGuavaCache<T> {
/**
* Description: 设置缓存值
* Date 2021-10-22 03:01:57
*
* @author yuyi
**/
default void putGuavaCache(String key, T value){
if(key == null || value == null){
return;
}
getCache().put(key, value);
}
/**
* Description: 获取缓存值
* Date 2021-10-22 03:02:25
*
* @author yuyi
**/
default T getGuavaCache(String key){
if(CuscStringUtils.isEmpty(key)){
return null;
}
return getCache().getIfPresent(key);
}
/**
* Description: 获取缓存对象
* <br />
* CreateDate 2021-11-19 11:44:01
*
* @author yuyi
**/
Cache<String, T> getCache();
}
package com.cusc.nirvana.user.ciam.util.crypt;
import java.math.BigInteger;
public class HexUtil
{
/**
* 整形转换成网络传输的字节流(字节数组)型数据
*
* @param num 一个整型数据
* @return 4个字节的自己数组
*/
public static byte[] intToBytes(int num)
{
byte[] bytes = new byte[4];
bytes[0] = (byte) (0xff & (num >> 0));
bytes[1] = (byte) (0xff & (num >> 8));
bytes[2] = (byte) (0xff & (num >> 16));
bytes[3] = (byte) (0xff & (num >> 24));
return bytes;
}
/**
* 四个字节的字节数据转换成一个整形数据
*
* @param bytes 4个字节的字节数组
* @return 一个整型数据
*/
public static int byteToInt(byte[] bytes)
{
int num = 0;
int temp;
temp = (0x000000ff & (bytes[0])) << 0;
num = num | temp;
temp = (0x000000ff & (bytes[1])) << 8;
num = num | temp;
temp = (0x000000ff & (bytes[2])) << 16;
num = num | temp;
temp = (0x000000ff & (bytes[3])) << 24;
num = num | temp;
return num;
}
/**
* 长整形转换成网络传输的字节流(字节数组)型数据
*
* @param num 一个长整型数据
* @return 4个字节的自己数组
*/
public static byte[] longToBytes(long num)
{
byte[] bytes = new byte[8];
for (int i = 0; i < 8; i++)
{
bytes[i] = (byte) (0xff & (num >> (i * 8)));
}
return bytes;
}
/**
* 大数字转换字节流(字节数组)型数据
*
* @param n
* @return
*/
public static byte[] byteConvert32Bytes(BigInteger n)
{
byte tmpd[] = (byte[])null;
if(n == null)
{
return null;
}
if(n.toByteArray().length == 33)
{
tmpd = new byte[32];
System.arraycopy(n.toByteArray(), 1, tmpd, 0, 32);
}
else if(n.toByteArray().length == 32)
{
tmpd = n.toByteArray();
}
else
{
tmpd = new byte[32];
for(int i = 0; i < 32 - n.toByteArray().length; i++)
{
tmpd[i] = 0;
}
System.arraycopy(n.toByteArray(), 0, tmpd, 32 - n.toByteArray().length, n.toByteArray().length);
}
return tmpd;
}
/**
* 换字节流(字节数组)型数据转大数字
*
* @param b
* @return
*/
public static BigInteger byteConvertInteger(byte[] b)
{
if (b[0] < 0)
{
byte[] temp = new byte[b.length + 1];
temp[0] = 0;
System.arraycopy(b, 0, temp, 1, b.length);
return new BigInteger(temp);
}
return new BigInteger(b);
}
/**
* 根据字节数组获得值(十六进制数字)
*
* @param bytes
* @return
*/
public static String getHexString(byte[] bytes)
{
return getHexString(bytes, true);
}
/**
* 根据字节数组获得值(十六进制数字)
*
* @param bytes
* @param upperCase
* @return
*/
public static String getHexString(byte[] bytes, boolean upperCase)
{
String ret = "";
for (int i = 0; i < bytes.length; i++)
{
ret += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1);
}
return upperCase ? ret.toUpperCase() : ret;
}
/**
* 打印十六进制字符串
*
* @param bytes
*/
public static void printHexString(byte[] bytes)
{
for (int i = 0; i < bytes.length; i++)
{
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1)
{
hex = '0' + hex;
}
System.out.print("0x" + hex.toUpperCase() + ",");
}
System.out.println("");
}
/**
* Convert hex string to byte[]
*
* @param hexString
* the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString)
{
if (hexString == null || hexString.equals(""))
{
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++)
{
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* Convert char to byte
*
* @param c
* char
* @return byte
*/
public static byte charToByte(char c)
{
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 用于建立十六进制字符的输出的小写字符数组
*/
private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 用于建立十六进制字符的输出的大写字符数组
*/
private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @return 十六进制char[]
*/
public static char[] encodeHex(byte[] data) {
return encodeHex(data, true);
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
* @return 十六进制char[]
*/
public static char[] encodeHex(byte[] data, boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制char[]
*/
protected static char[] encodeHex(byte[] data, char[] toDigits) {
int l = data.length;
char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @return 十六进制String
*/
public static String encodeHexString(byte[] data) {
return encodeHexString(data, true);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
* @return 十六进制String
*/
public static String encodeHexString(byte[] data, boolean toLowerCase) {
return encodeHexString(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制String
*/
protected static String encodeHexString(byte[] data, char[] toDigits) {
return new String(encodeHex(data, toDigits));
}
/**
* 将十六进制字符数组转换为字节数组
*
* @param data 十六进制char[]
* @return byte[]
* @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常
*/
public static byte[] decodeHex(char[] data) {
int len = data.length;
if ((len & 0x01) != 0) {
throw new RuntimeException("Odd number of characters.");
}
byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f = f | toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
/**
* 将十六进制字符转换成一个整数
*
* @param ch 十六进制char
* @param index 十六进制字符在字符数组中的位置
* @return 一个整数
* @throws RuntimeException 当ch不是一个合法的十六进制字符时,抛出运行时异常
*/
protected static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new RuntimeException("Illegal hexadecimal character " + ch
+ " at index " + index);
}
return digit;
}
/**
* 数字字符串转ASCII码字符串
*
* @param String
* 字符串
* @return ASCII字符串
*/
public static String StringToAsciiString(String content) {
String result = "";
int max = content.length();
for (int i = 0; i < max; i++) {
char c = content.charAt(i);
String b = Integer.toHexString(c);
result = result + b;
}
return result;
}
/**
* 十六进制转字符串
*
* @param hexString
* 十六进制字符串
* @param encodeType
* 编码类型4:Unicode,2:普通编码
* @return 字符串
*/
public static String hexStringToString(String hexString, int encodeType) {
String result = "";
int max = hexString.length() / encodeType;
for (int i = 0; i < max; i++) {
char c = (char) hexStringToAlgorism(hexString
.substring(i * encodeType, (i + 1) * encodeType));
result += c;
}
return result;
}
/**
* 十六进制字符串装十进制
*
* @param hex
* 十六进制字符串
* @return 十进制数值
*/
public static int hexStringToAlgorism(String hex) {
hex = hex.toUpperCase();
int max = hex.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = hex.charAt(i - 1);
int algorism = 0;
if (c >= '0' && c <= '9') {
algorism = c - '0';
} else {
algorism = c - 55;
}
result += Math.pow(16, max - i) * algorism;
}
return result;
}
/**
* 十六转二进制
*
* @param hex
* 十六进制字符串
* @return 二进制字符串
*/
public static String hexStringToBinary(String hex) {
hex = hex.toUpperCase();
String result = "";
int max = hex.length();
for (int i = 0; i < max; i++) {
char c = hex.charAt(i);
switch (c) {
case '0':
result += "0000";
break;
case '1':
result += "0001";
break;
case '2':
result += "0010";
break;
case '3':
result += "0011";
break;
case '4':
result += "0100";
break;
case '5':
result += "0101";
break;
case '6':
result += "0110";
break;
case '7':
result += "0111";
break;
case '8':
result += "1000";
break;
case '9':
result += "1001";
break;
case 'A':
result += "1010";
break;
case 'B':
result += "1011";
break;
case 'C':
result += "1100";
break;
case 'D':
result += "1101";
break;
case 'E':
result += "1110";
break;
case 'F':
result += "1111";
break;
}
}
return result;
}
/**
* ASCII码字符串转数字字符串
*
* @param String
* ASCII字符串
* @return 字符串
*/
public static String AsciiStringToString(String content) {
String result = "";
int length = content.length() / 2;
for (int i = 0; i < length; i++) {
String c = content.substring(i * 2, i * 2 + 2);
int a = hexStringToAlgorism(c);
char b = (char) a;
String d = String.valueOf(b);
result += d;
}
return result;
}
/**
* 将十进制转换为指定长度的十六进制字符串
*
* @param algorism
* int 十进制数字
* @param maxLength
* int 转换后的十六进制字符串长度
* @return String 转换后的十六进制字符串
*/
public static String algorismToHexString(int algorism, int maxLength) {
String result = "";
result = Integer.toHexString(algorism);
if (result.length() % 2 == 1) {
result = "0" + result;
}
return patchHexString(result.toUpperCase(), maxLength);
}
/**
* 字节数组转为普通字符串(ASCII对应的字符)
*
* @param bytearray
* byte[]
* @return String
*/
public static String byteToString(byte[] bytearray) {
String result = "";
char temp;
int length = bytearray.length;
for (int i = 0; i < length; i++) {
temp = (char) bytearray[i];
result += temp;
}
return result;
}
/**
* 二进制字符串转十进制
*
* @param binary
* 二进制字符串
* @return 十进制数值
*/
public static int binaryToAlgorism(String binary) {
int max = binary.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = binary.charAt(i - 1);
int algorism = c - '0';
result += Math.pow(2, max - i) * algorism;
}
return result;
}
/**
* 十进制转换为十六进制字符串
*
* @param algorism
* int 十进制的数字
* @return String 对应的十六进制字符串
*/
public static String algorismToHEXString(int algorism) {
String result = "";
result = Integer.toHexString(algorism);
if (result.length() % 2 == 1) {
result = "0" + result;
}
result = result.toUpperCase();
return result;
}
/**
* HEX字符串前补0,主要用于长度位数不足。
*
* @param str
* String 需要补充长度的十六进制字符串
* @param maxLength
* int 补充后十六进制字符串的长度
* @return 补充结果
*/
static public String patchHexString(String str, int maxLength) {
String temp = "";
for (int i = 0; i < maxLength - str.length(); i++) {
temp = "0" + temp;
}
str = (temp + str).substring(0, maxLength);
return str;
}
/**
* 将一个字符串转换为int
*
* @param s
* String 要转换的字符串
* @param defaultInt
* int 如果出现异常,默认返回的数字
* @param radix
* int 要转换的字符串是什么进制的,如16 8 10.
* @return int 转换后的数字
*/
public static int parseToInt(String s, int defaultInt, int radix) {
int i = 0;
try {
i = Integer.parseInt(s, radix);
} catch (NumberFormatException ex) {
i = defaultInt;
}
return i;
}
/**
* 将一个十进制形式的数字字符串转换为int
*
* @param s
* String 要转换的字符串
* @param defaultInt
* int 如果出现异常,默认返回的数字
* @return int 转换后的数字
*/
public static int parseToInt(String s, int defaultInt) {
int i = 0;
try {
i = Integer.parseInt(s);
} catch (NumberFormatException ex) {
i = defaultInt;
}
return i;
}
/**
* 十六进制串转化为byte数组
*
* @return the array of byte
*/
public static byte[] hexToByte(String hex)
throws IllegalArgumentException {
if (hex.length() % 2 != 0) {
throw new IllegalArgumentException();
}
char[] arr = hex.toCharArray();
byte[] b = new byte[hex.length() / 2];
for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
String swap = "" + arr[i++] + arr[i];
int byteint = Integer.parseInt(swap, 16) & 0xFF;
b[j] = new Integer(byteint).byteValue();
}
return b;
}
/**
* 字节数组转换为十六进制字符串
*
* @param b
* byte[] 需要转换的字节数组
* @return String 十六进制字符串
*/
public static String byteToHex(byte b[]) {
if (b == null) {
throw new IllegalArgumentException(
"Argument b ( byte array ) is null! ");
}
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xff);
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
public static byte[] subByte(byte[] input, int startIndex, int length) {
byte[] bt = new byte[length];
for (int i = 0; i < length; i++) {
bt[i] = input[i + startIndex];
}
return bt;
}
}
package com.cusc.nirvana.user.ciam.util.crypt;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;
/**
* Description: 国密SM4
* <br />
* BC库从1.59版本开始已经基本实现了国密算法(SM2、SM3、SM4)
* CreateDate 2021-11-17 14:37
*
* @author yuyi
**/
public class Sm4Util {
private static final Logger LOGGER = LoggerFactory.getLogger(Sm4Util.class);
//算法名称
public static final String ALGORITHM_NAME = "SM4";
//ECB P5填充
public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
//CBC P5填充
public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS5Padding";
//密钥长度
public static final int DEFAULT_KEY_SIZE = 128;
static {
Security.addProvider(new BouncyCastleProvider());
}
private Sm4Util() {
}
/**
* 获取密钥
*
* @return byte
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
*/
public static byte[] generateKey() throws NoSuchAlgorithmException, NoSuchProviderException {
return generateKey(DEFAULT_KEY_SIZE);
}
/**
* 获取指定长度密钥
*
* @param keySize 密钥的长度
* @return byte
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
*/
public static byte[] generateKey(int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
kg.init(keySize, new SecureRandom());
return kg.generateKey().getEncoded();
}
/**
* ECB P5填充加密
*
* @param key 密钥
* @param data 明文数据
* @return byte
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public static byte[] encryptEcbPaddingByte(byte[] key, byte[] data)
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}
/**
* Description: ecb加密
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String encryptEcbPadding(String key, String data) {
return encryptEcbPaddingHex(key, data, false, null);
}
/**
* Description: ecb加密,可以指定混淆
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String encryptEcbPaddingHex(String key, String data, boolean hexString, String charset) {
if (CuscStringUtils.isEmpty(data)) {
return null;
}
try {
byte[] keyBytes;
if (hexString) {
keyBytes = HexUtil.hexStringToBytes(key);
} else {
keyBytes = key.getBytes();
}
byte[] dataBytes;
if (CuscStringUtils.isNotEmpty(charset)) {
dataBytes = data.getBytes(charset);
} else {
dataBytes = data.getBytes(StandardCharsets.UTF_8);
}
byte[] encrypted = encryptEcbPaddingByte(keyBytes, dataBytes);
return base64Encoder(encrypted);
} catch (Exception e) {
LOGGER.error("Sm4Util.encryptEcbPaddingHex error ! ", e);
return null;
}
}
/**
* ECB P5填充解密
*
* @param key 密钥
* @param cipherText 加密后的数据
* @return byte
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
*/
public static byte[] decryptEcbPaddingByte(byte[] key, byte[] cipherText)
throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException {
Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
return cipher.doFinal(cipherText);
}
/**
* Description: ecb解密
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String decryptEcbPadding(String key, String data) {
return decryptEcbPaddingHex(key, data, false, null);
}
/**
* Description: ecb解密,可以指定混淆
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String decryptEcbPaddingHex(String key, String data, boolean hexString, String charset) {
if (CuscStringUtils.isEmpty(data)) {
return null;
}
try {
byte[] keyBytes;
if (hexString) {
keyBytes = HexUtil.hexStringToBytes(key);
} else {
keyBytes = key.getBytes();
}
byte[] decrypted = decryptEcbPaddingByte(keyBytes, base64Decoder(data));
if (CuscStringUtils.isNotEmpty(charset)) {
return new String(decrypted, charset);
}
return new String(decrypted, StandardCharsets.UTF_8);
} catch (Exception e) {
LOGGER.error("Sm4Util.decryptEcbPaddingHex error ! ", e);
return null;
}
}
/**
* CBC P5填充加密
*
* @param key 密钥
* @param iv 偏移量
* @param data 明文数据
* @return byte
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws InvalidAlgorithmParameterException
*/
public static byte[] encryptCbcPaddingByte(byte[] key, byte[] iv, byte[] data)
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
Cipher cipher = generateCbcCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(data);
}
/**
* Description: cbc加密
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String encryptCbcPadding(String key, String data, String iv) {
return encryptCbcPaddingHex(key, data, iv, false, null);
}
/**
* Description: cbc加密,可以指定混淆
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String encryptCbcPaddingHex(String key, String data, String iv, boolean hexString, String charset) {
if (CuscStringUtils.isEmpty(data)) {
return null;
}
try {
byte[] keyBytes;
byte[] ivBytes;
if (hexString) {
keyBytes = HexUtil.hexStringToBytes(key);
ivBytes = HexUtil.hexStringToBytes(iv);
} else {
keyBytes = key.getBytes();
ivBytes = iv.getBytes();
}
byte[] dataBytes;
if (CuscStringUtils.isNotEmpty(charset)) {
dataBytes = data.getBytes(charset);
} else {
dataBytes = data.getBytes(StandardCharsets.UTF_8);
}
byte[] encrypted = encryptCbcPaddingByte(keyBytes, ivBytes, dataBytes);
return base64Encoder(encrypted);
} catch (Exception e) {
LOGGER.error("Sm4Util.encryptCbcPaddingHex error ! ", e);
return null;
}
}
/**
* CBC P5填充解密
*
* @param key 密钥
* @param iv 偏移量
* @param cipherText 加密数据
* @return byte
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
*/
public static byte[] decryptCbcPaddingByte(byte[] key, byte[] iv, byte[] cipherText)
throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException,
NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException {
Cipher cipher = generateCbcCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(cipherText);
}
/**
* Description: cbc解密
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String decryptCbcPadding(String key, String data, String iv) {
return decryptCbcPaddingHex(key, data, iv, false, null);
}
/**
* Description: cbc解密,可以指定混淆
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String decryptCbcPaddingHex(String key, String data, String iv, boolean hexString, String charset) {
if (CuscStringUtils.isEmpty(data)) {
return null;
}
try {
byte[] keyBytes;
byte[] ivBytes;
if (hexString) {
keyBytes = HexUtil.hexStringToBytes(key);
ivBytes = HexUtil.hexStringToBytes(iv);
} else {
keyBytes = key.getBytes();
ivBytes = iv.getBytes();
}
byte[] decrypted = decryptCbcPaddingByte(keyBytes, ivBytes, base64Decoder(data));
if (CuscStringUtils.isNotEmpty(charset)) {
return new String(decrypted, charset);
}
return new String(decrypted, StandardCharsets.UTF_8);
} catch (Exception e) {
LOGGER.error("Sm4Util.decryptCbcPaddingHex error ! ", e);
return null;
}
}
/**
* ECB P5填充加解密Cipher初始化
*
* @param algorithmName 算法名称
* @param mode 1 加密 2解密
* @param key 密钥
* @return Cipher
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
*/
private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key)
throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException {
Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
cipher.init(mode, sm4Key);
return cipher;
}
/**
* CBC P5填充加解密Cipher初始化
*
* @param algorithmName 算法名称
* @param mode 1 加密 2解密
* @param key 密钥
* @param iv 偏移量
* @return Cipher
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
*/
private static Cipher generateCbcCipher(String algorithmName, int mode, byte[] key, byte[] iv)
throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
NoSuchProviderException, NoSuchPaddingException {
Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(mode, sm4Key, ivParameterSpec);
return cipher;
}
/**
* Description: base64编码
* <br />
* CreateDate 2021-11-17 15:54:52
*
* @author yuyi
**/
private static String base64Encoder(byte[] encrypted) {
return Base64.getEncoder().encodeToString(encrypted);
}
/**
* Description: base64解码
* <br />
* CreateDate 2021-11-17 17:44:13
*
* @author yuyi
**/
private static byte[] base64Decoder(String encrypted) throws IOException {
return Base64.getDecoder().decode(encrypted);
}
}
package com.cusc.nirvana.user.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* Description: 异步线程池配置
* <br />
* CreateDate 2021-12-01 17:25
*
* @author yuy336
**/
@Configuration
@EnableAsync
public class ExecutorConfig {
private final static Logger LOGGER = LoggerFactory.getLogger(ExecutorConfig.class);
/**
* Description: 刷新数据到redis线程池
* <br />
* CreateDate 2021-12-01 17:27:11
*
* @author yuyi
**/
@Bean("dataToRedisExecutor")
public Executor dataToRedisExecutor() {
LOGGER.info("init dataToRedisExecutor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(2);
//配置最大线程数
executor.setMaxPoolSize(10);
//配置队列大小
executor.setQueueCapacity(1000);
//允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(60);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("data-to-redis");
//线程池的饱和策略 我这里设置的是 CallerRunsPolicy 也就是由用调用者所在的线程来执行任务 共有四种
//AbortPolicy:直接抛出异常,这是默认策略;
//CallerRunsPolicy:用调用者所在的线程来执行任务;
//DiscardOldestPolicy:丢弃阻塞队列中靠最前的任务,并执行当前任务;
//DiscardPolicy:直接丢弃任务;
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
}
package com.cusc.nirvana.user.config;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.util.concurrent.TimeUnit;
/**
* Description: user-auth调用外部的配置
* <br />
* CreateDate 2022-01-28 17:14
*
* @author yuy336
**/
@Configuration
@Slf4j
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return getRestTemplate();
}
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
return restTemplate;
}
private ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
private HttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
//设置整个连接池最大连接数
connectionManager.setMaxTotal(100);
//路由是对maxTotal的细分
connectionManager.setDefaultMaxPerRoute(100);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(10000) //返回数据的超时时间
.setConnectTimeout(1000) //连接上服务器的超时时间
.setConnectionRequestTimeout(500) //从连接池中获取连接的超时时间
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
//设置后台线程剔除失效连接
.evictExpiredConnections()
.evictIdleConnections(10, TimeUnit.SECONDS)
.build();
}
}
package com.cusc.nirvana.user.config;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.eiam.constants.ResponseCode;
import com.cusc.nirvana.user.exception.CuscUserException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Order(0)
public class RnrUserExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(RnrUserExceptionHandler.class);
@ExceptionHandler(CuscUserException.class)
@ResponseStatus(HttpStatus.OK)
public Response excpetionHandler(CuscUserException e) {
log.warn("CuscUserException Handler:code {}, description: {}", e.getCode(), e.getMessage());
return Response.createError(e.getMessage(), StringUtils.isBlank(e.getCode()) ? ResponseCode.SYSTEM_ERROR.getCode() : Integer.parseInt(e.getCode()));
}
}
package com.cusc.nirvana.user.config;
/**
* 签名静态属性
*/
public class SignConstants {
/**应用ID的key名称*/
public final static String APP_ID = "APPID";
/**随机数key*/
public final static String NONCE_STR = "NONCE_STR";
/**时间戳key*/
public final static String TIMESTAMP = "TIMESTAMP";
/**版本key*/
public final static String VERSION = "VERSION";
/**签名key*/
public final static String SIGN = "SIGN";
}
package com.cusc.nirvana.user.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* Description: 短信相关常量类
* <br />
* CreateDate 2021-11-03 20:36
*
* @author yuyi
**/
@Component
public class SmsPropertyConfig {
//短信的url,默认值是测试环境
@Value("${sms.cusc.url:}")
public String smsUrl;
//短信发送的url
@Value("${sms.cusc.sendUrl:/sms/v1/send}")
public String sendUrl;
//短信发送结果查询的url
@Value("${sms.cusc.sendResultQueryUrl:/sms/v1/list}")
public String sendResultQueryUrl;
@Value("${sms.cusc.version:1.0.0}")
private String VERSION;
@Value("${sms.cusc.appid:78F985EE0C6F4418B73013D2B5C48AB2}")
private String APPID;
@Value("${sms.cusc.appsecret:6C0768AA4CE64AC3893A0F0F280571A6}")
private String APPSCRET;
//短信平台的访问key
@Value("${sms.cusc.accessKey:}")
public String accessKey;
//短信平台的strategyCode
@Value("${sms.cusc.signatureCode:}")
public String signatureCode;
//短信验证码错误次数
@Value("${sms.cusc.errorCount:3}")
public Integer errorCount;
public String getSmsUrl() {
return smsUrl;
}
public void setSmsUrl(String smsUrl) {
this.smsUrl = smsUrl;
}
public String getSendUrl() {
return sendUrl;
}
public void setSendUrl(String sendUrl) {
this.sendUrl = sendUrl;
}
public String getSendResultQueryUrl() {
return sendResultQueryUrl;
}
public void setSendResultQueryUrl(String sendResultQueryUrl) {
this.sendResultQueryUrl = sendResultQueryUrl;
}
public String getAPPID() {
return APPID;
}
public void setAPPID(String APPID) {
this.APPID = APPID;
}
public String getAPPSCRET() {
return APPSCRET;
}
public void setAPPSCRET(String APPSCRET) {
this.APPSCRET = APPSCRET;
}
public String getVERSION() {
return VERSION;
}
public void setVERSION(String VERSION) {
this.VERSION = VERSION;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSignatureCode() {
return signatureCode;
}
public void setSignatureCode(String signatureCode) {
this.signatureCode = signatureCode;
}
public Integer getErrorCount() {
return errorCount;
}
public void setErrorCount(Integer errorCount) {
this.errorCount = errorCount;
}
}
package com.cusc.nirvana.user.config;
import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* Description: mvc日志输出
* <br />
* CreateDate 2021-11-12 10:26
*
* @author yuyi
**/
@Aspect
@Component
public class WebLogAspect {
private final static Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);
/**
* 以 controller 包下定义的所有请求为切入点
*/
@Pointcut("execution(* com.cusc.nirvana.user.*.*.controller.*.*(..))")
public void webLog() {
}
/**
* 环绕
*
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("webLog()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
String requestId = CuscStringUtils.generateUuid();
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = sra.getRequest();
String url = request.getRequestURL().toString();
String method = request.getMethod();
String params = "";
//获取请求参数集合并进行遍历拼接
if ("POST".equals(method)) {
Object[] args = proceedingJoinPoint.getArgs();
params = JSON.toJSONString(args);
} else if ("GET".equals(method)) {
params = request.getQueryString();
}
LOGGER.info("requestId:{} , request url:{} , method:{} , params:{}", requestId, url, method, params);
// result的值就是被拦截方法的返回值
Object result = proceedingJoinPoint.proceed();
LOGGER.info("requestId:{} , response url:{} , result:{} , cost:{} ms", requestId, url,
JSON.toJSONString(result),
System.currentTimeMillis() - startTime);
return result;
}
}
package com.cusc.nirvana.user.eiam.common;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* iam的DO基类
* </p>
*
* @author yuyi
* @since 2021-10-21
*/
public class BaseIamPO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 逻辑删除(0-未删除,1-已删除)
*/
@TableField("is_delete")
private Integer isDelete;
/**
* 创建时间
*/
@TableField(value = "create_time", insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER)
private Date createTime;
/**
* 更新时间
*/
@TableField(value = "update_time", insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER)
private Date updateTime;
/**
* 创建人
*/
@TableField(value = "creator", updateStrategy = FieldStrategy.NEVER)
private String creator;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
@Override
public String toString() {
return "BaseIamDO{" +
"id=" + id +
", isDelete=" + isDelete +
", createTime=" + createTime +
", updateTime=" + updateTime +
", creator='" + creator + '\'' +
'}';
}
}
package com.cusc.nirvana.user.eiam.constants;
/**
* Description: redis相关常量类
* <br />
* CreateDate 2021-11-03 20:36
*
* @author yuyi
**/
public class EiamConstant {
//url的是否鉴权-鉴权
public static final int URL_IS_AUTH_YES = 0;
//url的是否鉴权-不鉴权
public static final int URL_IS_AUTH_NO = 1;
//默认的组织和岗位
public static final String DEFAULT_ORGAN_POSTION = "0";
public static final String QUERY_CODE_SEPARATOR = "-";
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment