项目工具类

Base64工具类
public class Base64ConvertUtil {

/**
* 加密JDK1.8
*/
public static String encode(String str) throws UnsupportedEncodingException {
byte[] encodeBytes = Base64.getEncoder().encode(str.getBytes("utf-8"));
return new String(encodeBytes);
}

/**
* 解密JDK1.8
*/
public static String decode(String str) throws UnsupportedEncodingException {
byte[] decodeBytes = Base64.getDecoder().decode(str.getBytes("utf-8"));
return new String(decodeBytes);
}

}
/**
* 进制转换工具
*/
public class HexConvertUtil {


private static final Integer INTEGER_1 = 1;


private static final Integer INTEGER_2 = 2;

/**
* 将二进制转换成16进制
*/
public static String parseByte2HexStr(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (byte buff : bytes) {
String hex = Integer.toHexString(buff & 0xFF);
if (hex.length() == INTEGER_1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}

/**
* 将16进制转换为二进制
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < INTEGER_1) {
return null;
}
byte[] result = new byte[hexStr.length() / INTEGER_2];
for (int i = 0, len = hexStr.length() / INTEGER_2; i < len; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}

/**
* Json和Object的互相转换,转List必须Json最外层加[],转Object,Json最外层不要加[]
*/
public class JsonConvertUtil {
/**
* JSON 转 Object
*/
public static <T> T jsonToObject(String pojo, Class<T> clazz) {
return JSONObject.parseObject(pojo, clazz);
}

/**
* Object 转 JSON
*/
public static <T> String objectToJson(T t){
return JSONObject.toJSONString(t);
}
}
/**
* Properties工具
*/
public class PropertiesUtil {


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

private static final Properties PROP = new Properties();

public static void readProperties(String fileName) {
InputStream in = null;
try {
in = PropertiesUtil.class.getResourceAsStream("/" + fileName);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
PROP.load(bf);
} catch (IOException e) {
logger.error("PropertiesUtil工具类读取配置文件出现IOException异常:" + e.getMessage());
throw new CustomException("PropertiesUtil工具类读取配置文件出现IOException异常:" + e.getMessage());
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
logger.error("PropertiesUtil工具类读取配置文件出现IOException异常:" + e.getMessage());
throw new CustomException("PropertiesUtil工具类读取配置文件出现IOException异常:" + e.getMessage());
}
}
}

public static String getProperty(String key){
return PROP.getProperty(key);
}
}

/**
* Serializable工具(JDK)(也可以使用Protobuf自行百度)
*/
public class SerializableUtil {

/**
* logger
*/
private static final Logger logger = LoggerFactory.getLogger(SerializableUtil.class);

/**
* 序列化
*/
public static byte[] serializable(Object object) {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
return baos.toByteArray();
} catch (IOException e) {
logger.error("SerializableUtil工具类序列化出现IOException异常:" + e.getMessage());
throw new CustomException("SerializableUtil工具类序列化出现IOException异常:" + e.getMessage());
} finally {
try {
if (oos != null) {
oos.close();
}
if (baos != null) {
baos.close();
}
} catch (IOException e) {
logger.error("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
throw new CustomException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
}
}
}

/**
* 反序列化
*/
public static Object unserializable(byte[] bytes) {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (ClassNotFoundException e) {
logger.error("SerializableUtil工具类反序列化出现ClassNotFoundException异常:" + e.getMessage());
throw new CustomException("SerializableUtil工具类反序列化出现ClassNotFoundException异常:" + e.getMessage());
} catch (IOException e) {
logger.error("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
throw new CustomException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
} finally {
try {
if (ois != null) {
ois.close();
}
if (bais != null) {
bais.close();
}
} catch (IOException e) {
logger.error("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
throw new CustomException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
}
}
}

}

/**
* String工具
*/
public class StringUtil {
/**
* 定义下划线
*/
private static final char UNDERLINE = '_';

/**
* String为空判断(不允许空格)
*/
public static boolean isBlank(String str) {
return str == null || "".equals(str.trim());
}

/**
* String不为空判断(不允许空格)
*/
public static boolean isNotBlank(String str) {
return !isBlank(str);
}

/**
* Byte数组为空判断
*/
public static boolean isNull(byte[] bytes) {
// 根据byte数组长度为0判断
return bytes == null || bytes.length == 0;
}

/**
* Byte数组不为空判断
*/
public static boolean isNotNull(byte[] bytes) {
return !isNull(bytes);
}

/**
* 驼峰转下划线工具
* @param param
*/
public static String camelToUnderline(String param) {
if (isNotBlank(param)) {
int len = param.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (Character.isUpperCase(c)) {
sb.append(UNDERLINE);
sb.append(Character.toLowerCase(c));
} else {
sb.append(c);
}
}
return sb.toString();
} else {
return "";
}
}

/**
* 下划线转驼峰工具
*/
public static String underlineToCamel(String param) {
if (isNotBlank(param)) {
int len = param.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (c == 95) {
++i;
if (i < len) {
sb.append(Character.toUpperCase(param.charAt(i)));
}
} else {
sb.append(c);
}
}
return sb.toString();
} else {
return "";
}
}

/**
* 在字符串两周添加''
*/
public static String addSingleQuotes(String param) {
return "\'" + param + "\'";
}
}
/**
* AES加密解密工具类
*/
@Component
public class AesCipherUtil {

/**
* AES密码加密私钥(Base64加密)
*/
private static String encryptAESKey;
// private static final byte[] KEY = { 1, 1, 33, 82, -32, -85, -128, -65 };

@Value("${encryptAESKey}")
public void setEncryptAESKey(String encryptAESKey) {
AesCipherUtil.encryptAESKey = encryptAESKey;
}

/**
* logger
*/
private static final Logger logger = LoggerFactory.getLogger(AesCipherUtil.class);

/**
* 加密
*/
public static String enCrypto(String str) {
try {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
// 实例化支持AES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
// KeyGenerator 提供对称密钥生成器的功能,支持各种算法
KeyGenerator keygen = KeyGenerator.getInstance("AES");
// 将私钥encryptAESKey先Base64解密后转换为byte[]数组按128位初始化
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(Base64ConvertUtil.decode(encryptAESKey).getBytes());
keygen.init(128, secureRandom);
// SecretKey 负责保存对称密钥 生成密钥
SecretKey desKey = keygen.generateKey();
// 生成Cipher对象,指定其支持的AES算法,Cipher负责完成加密或解密工作
Cipher c = Cipher.getInstance("AES");
// 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
c.init(Cipher.ENCRYPT_MODE, desKey);
byte[] src = str.getBytes();
// 该字节数组负责保存加密的结果
byte[] cipherByte = c.doFinal(src);
// 先将二进制转换成16进制,再返回Base64加密后的String
return Base64ConvertUtil.encode(HexConvertUtil.parseByte2HexStr(cipherByte));
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
logger.error("getInstance()方法异常:" + e.getMessage());
throw new CustomUnauthorizedException("getInstance()方法异常:" + e.getMessage());
} catch (UnsupportedEncodingException e) {
logger.error("Base64加密异常:" + e.getMessage());
throw new CustomUnauthorizedException("Base64加密异常:" + e.getMessage());
} catch (InvalidKeyException e) {
logger.error("初始化Cipher对象异常:" + e.getMessage());
throw new CustomUnauthorizedException("初始化Cipher对象异常:" + e.getMessage());
} catch (IllegalBlockSizeException | BadPaddingException e) {
logger.error("加密异常,密钥有误:" + e.getMessage());
throw new CustomUnauthorizedException("加密异常,密钥有误:" + e.getMessage());
}
}

/**
* 解密
*/
public static String deCrypto(String str) {
try {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
// 实例化支持AES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
// KeyGenerator 提供对称密钥生成器的功能,支持各种算法
KeyGenerator keygen = KeyGenerator.getInstance("AES");
// 将私钥encryptAESKey先Base64解密后转换为byte[]数组按128位初始化
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(Base64ConvertUtil.decode(encryptAESKey).getBytes());
keygen.init(128, secureRandom);
// SecretKey 负责保存对称密钥 生成密钥
SecretKey desKey = keygen.generateKey();
// 生成Cipher对象,指定其支持的AES算法,Cipher负责完成加密或解密工作
Cipher c = Cipher.getInstance("AES");
// 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示解密模式
c.init(Cipher.DECRYPT_MODE, desKey);
// 该字节数组负责保存解密的结果,先对str进行Base64解密,将16进制转换为二进制
byte[] cipherByte = c.doFinal(HexConvertUtil.parseHexStr2Byte(Base64ConvertUtil.decode(str)));
return new String(cipherByte);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
logger.error("getInstance()方法异常:" + e.getMessage());
throw new CustomUnauthorizedException("getInstance()方法异常:" + e.getMessage());
} catch (UnsupportedEncodingException e) {
logger.error("Base64解密异常:" + e.getMessage());
throw new CustomUnauthorizedException("Base64解密异常:" + e.getMessage());
} catch (InvalidKeyException e) {
logger.error("初始化Cipher对象异常:" + e.getMessage());
throw new CustomUnauthorizedException("初始化Cipher对象异常:" + e.getMessage());
} catch (IllegalBlockSizeException | BadPaddingException e) {
logger.error("解密异常,密钥有误:" + e.getMessage());
throw new CustomUnauthorizedException("解密异常,密钥有误:" + e.getMessage());
}
}
}
/**
* JAVA-JWT工具类
*/
@Component
public class JwtUtil {

/**
* logger
*/
private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

/**
* 过期时间改为从配置文件获取
*/
private static String accessTokenExpireTime;

/**
* JWT认证加密私钥(Base64加密)
*/
private static String encryptJWTKey;

@Value("${accessTokenExpireTime}")
public void setAccessTokenExpireTime(String accessTokenExpireTime) {
JwtUtil.accessTokenExpireTime = accessTokenExpireTime;
}

@Value("${encryptJWTKey}")
public void setEncryptJWTKey(String encryptJWTKey) {
JwtUtil.encryptJWTKey = encryptJWTKey;
}

/**
* 校验token是否正确
*/
public static boolean verify(String token) {
try {
// 帐号加JWT私钥解密
String secret = getClaim(token, Constant.ACCOUNT) + Base64ConvertUtil.decode(encryptJWTKey);
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm)
.build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (UnsupportedEncodingException e) {
logger.error("JWTToken认证解密出现UnsupportedEncodingException异常:" + e.getMessage());
throw new CustomException("JWTToken认证解密出现UnsupportedEncodingException异常:" + e.getMessage());
}
}

/**
* 获得Token中的信息无需secret解密也能获得
*/
public static String getClaim(String token, String claim) {
try {
DecodedJWT jwt = JWT.decode(token);
// 只能输出String类型,如果是其他类型返回null
return jwt.getClaim(claim).asString();
} catch (JWTDecodeException e) {
logger.error("解密Token中的公共信息出现JWTDecodeException异常:" + e.getMessage());
throw new CustomException("解密Token中的公共信息出现JWTDecodeException异常:" + e.getMessage());
}
}

/**
* 生成签名
*/
public static String sign(String account, String currentTimeMillis) {
try {
// 帐号加JWT私钥加密
String secret = account + Base64ConvertUtil.decode(encryptJWTKey);
// 此处过期时间是以毫秒为单位,所以乘以1000
Date date = new Date(System.currentTimeMillis() + Long.parseLong(accessTokenExpireTime) * 1000);
Algorithm algorithm = Algorithm.HMAC256(secret);
// 附带account帐号信息
return JWT.create()
.withClaim("account", account)
.withClaim("currentTimeMillis", currentTimeMillis)
.withExpiresAt(date)
.sign(algorithm);
} catch (UnsupportedEncodingException e) {
logger.error("JWTToken加密出现UnsupportedEncodingException异常:" + e.getMessage());
throw new CustomException("JWTToken加密出现UnsupportedEncodingException异常:" + e.getMessage());
}
}
}

/**
* 获取当前登录用户工具类
*/
@Component
public class UserUtil {

private final UsersMapper userMapper;

@Autowired
public UserUtil(UsersMapper userMapper) {
this.userMapper = userMapper;
}

/**
* 获取当前登录用户
* @param
*/
public UsersDto getUser() {
String token = SecurityUtils.getSubject().getPrincipal().toString();
// 解密获得Account
String account = JwtUtil.getClaim(token, Constant.ACCOUNT);
UsersDto usersDto = new UsersDto();
usersDto.setAccount(account);
usersDto = userMapper.selectOne(usersDto);
// 用户是否存在
if (usersDto == null) {
throw new CustomException("该帐号不存在(The account does not exist.)");
}
return usersDto;
}

/**
* 获取当前登录用户Id
* @param
*/
public Integer getUserId() {
return getUser().getId();
}

/**
* 获取当前登录用户Token
* @param
*/
public String getToken() {
return SecurityUtils.getSubject().getPrincipal().toString();
}

/**
* 获取当前登录用户Account
*/
public String getAccount() {
String token = SecurityUtils.getSubject().getPrincipal().toString();
// 解密获得Account
return JwtUtil.getClaim(token, Constant.ACCOUNT);
}
}
posted @ 2019-09-27 20:38  薄情的树先生  阅读(530)  评论(0编辑  收藏  举报