項目工具類

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());
}
}
}
/** * 獲取當前登陸用戶工具類 */@Componentpublic 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);    }}
相關文章
相關標籤/搜索