Project Tools

Base64 Tools
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);
}

}
/ ** 
* binary conversion tools
* /
public class HexConvertUtil {


Private static integer_1 = Integer Final. 1;


Private static Integer Final integer_2 = 2;

/ **
* converted into a binary hexadecimal
* /
public static String parseByte2HexStr (byte [ ] bytes) {
the StringBuffer the StringBuffer new new SB = ();
for (BUFF byte: bytes) {
String hex = Integer.toHexString (BUFF & 0xFF);
IF (hex.length () == integer_1) {
hex = '0' + hex;
}
sb.append (hex.toUpperCase ());
}
return sb.toString ();
}

/ **
* 16 hexadecimal to binary
*/
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;
}
}

/ **
* Object Json and mutual conversion, the outermost turn Json List must add [], Object turn, the outermost layer do not add Json []
* /
public class JsonConvertUtil {
/ **
* the JSON revolutions Object
* /
public static <T> T jsonToObject (POJO String, Class <T> clazz) {
return JSONObject.parseObject (POJO, clazz);
}

/ **
* Object turn the JSON
* /
public static <T> String objectToJson (T T) {
return the 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 tools read the configuration file appears an IOException:" + e.getMessage ());
} {the finally
the try {
IF (! in = null) {
in.close ();
}
} the catch (IOException E ) {
logger.error ( "PropertiesUtil tools read the configuration file appears an IOException:" + e.getMessage ());
the throw new new customException ( "PropertiesUtil tools read the configuration file appears an 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 tools appear sequence of an IOException:" + e.getMessage ());
the throw new new customException ( "serialized SerializableUtil tools appear an IOException:" + e.getMessage ());
} {the finally
the try {
IF (OOS = null!) {
oos.close ();
}
IF (BAOS = null!) {
baos.close ();
}
} the catch (IOException E) {
logger.error ( "tools SerializableUtil deserialization occurs an IOException: "+ e.getMessage ());
the throw new new customException (" tools SerializableUtil deserialization occurs an IOException: "+ e.getMessage ());
}
}
}

/ **
* deserialize
* /
public static Object unserializable (byte [] bytes) {
A ByteArrayInputStream Bais = null;
the ObjectInputStream OIS = null;
the try {
Bais new new = A ByteArrayInputStream (bytes);
OIS = new new the ObjectInputStream (Bais);
return OIS .readObject ();
} the catch (ClassNotFoundException E) {
logger.error ( "tools SerializableUtil deserialization occurs a ClassNotFoundException:" + e.getMessage ());
the throw new new customException ( "tools SerializableUtil deserialization occurs a ClassNotFoundException : "+ e.getMessage ());
} the catch (IOException E) {
logger.error ( "SerializableUtil tools deserialization occurs an IOException:" + e.getMessage ());
the throw new new customException ( "Tools SerializableUtil deserialization occurs an IOException:" + e.getMessage ());
} the finally {
the try {
IF (OIS = null!) {
ois.close ();
}
IF (Bais = null!) {
bais.close ();
}
} the catch (IOException E) {
logger.error ( "tools deserialization SerializableUtil emergence of an IOException: "+ e.getMessage ());
the throw new new customException (" tools SerializableUtil deserialization occurs an IOException: "+ e.getMessage ());
}
}
}

}

/ **
* Tool String
* /
public of StringUtil class {
/ **
* defined underlined
* /
Private Final static char UNDERLINE = '_';

/ **
* String is empty is determined (no space)
* /
public static Boolean of isBlank ( STR String) {
return STR == null || "" .equals (str.trim ());
}

/ **
* String determination is not empty (no space)
* /
public static Boolean isNotBlank (String STR) {
return ! of isBlank (STR);
}

/ **
* byte array is empty judgment
* /
public static Boolean isNull (byte [] bytes) {
// The length of the array is byte 0 is determined
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 + "\'";
}
}
/ ** 
* the AES encryption and decryption tools
* /
@Component
public class AesCipherUtil {

/ **
* the AES cipher encryption private key (the Base64 encryption)
* /
Private static String encryptAESKey;
// Private Final static byte [] = {KEY. 1, . 1, 33 is, 82, -32, -85, -128, -65};

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

/ **
* Logger
* /
Private static Logger Logger = Final LoggerFactory.getLogger (AesCipherUtil.class);

/ **
* encryption
* /
public static String enCrypto (String STR) {
the try {
Security.addProvider (new new com.sun.crypto.provider.SunJCE ());
// instantiate support key generator AES algorithm (named after the algorithm regulations required, otherwise throw an exception)
// KeyGenerator provide symmetric key generator, support a variety of algorithms
the KeyGenerator keygen = KeyGenerator.getInstance ( "the AES");
// convert the private key byte [] arrays are initialized encryptAESKey 128 decrypts the first Base64
secureRandom secureRandom = SecureRandom.getInstance ( "SHA1PRNG ");
secureRandom.setSeed (Base64ConvertUtil.decode (encryptAESKey) .getBytes ());
keygen.init (128, secureRandom);
// save a SecretKey responsible for symmetric key generation key
a SecretKey DESKey keygen.generateKey = ();
// generate Cipher object that specifies it supports AES algorithm, Cipher is responsible for the completion of the encryption or decryption work
Cipher c = Cipher.getInstance ( "AES" );
// The key, Cipher object is initialized, ENCRYPT_MODE represents an encryption mode
c.init (Cipher.ENCRYPT_MODE, DESKey);
byte [] str.getBytes the src = ();
// save the byte array is responsible for encrypting the result
byte [] = cipherByte c.doFinal (the src);
// hexadecimal is converted into binary first, after the return Base64 encryption String
return Base64ConvertUtil.encode (HexConvertUtil.parseByte2HexStr (cipherByte));
} the catch (NoSuchAlgorithmException | a NoSuchPaddingException E) {
logger.error ( "the getInstance () method exception:" + e.getMessage ());
the throw new new CustomUnauthorizedException ( "the getInstance () method exception:" + e.getMessage ());
} the catch (UnsupportedEncodingException E) {
Logger. error ( "Base64 encryption exception:" + e.getMessage ());
throw new CustomUnauthorizedException ( "Base64 encryption Exception:" + e.getMessage ());
} the catch (InvalidKeyException E) {
logger.error ( "Cipher object is initialized Exception:" + e.getMessage ());
the throw new new CustomUnauthorizedException ( "Initialization Cipher object exception: "+ e.getMessage ());
} the catch (IllegalBlockSizeException | BadPaddingException E) {
logger.error (" abnormal encryption key error: "+ e.getMessage ());
the throw new new CustomUnauthorizedException (" encryption abnormal key error: "+ e.getMessage ());
}
}

/ **
* decryption
* /
public static String deCrypto (String STR) {
the try {
Security.addProvider (new new com.sun.crypto.provider.SunJCE ());
// instantiate support key generator AES algorithm (named after the algorithm regulations required, otherwise throw an exception)
// KeyGenerator provide symmetric key generator function, support a variety of algorithms
KeyGenerator keygen = KeyGenerator.getInstance ( "AES ");
// private key to decrypt encryptAESKey first Base64 converted to byte [] array 128 by initializing
a secureRandom secureRandom = SecureRandom.getInstance (" SHA1PRNG ");
secureRandom.setSeed (Base64ConvertUtil.decode (encryptAESKey) .getBytes ()) ;
keygen.init (128, secureRandom);
// save a SecretKey responsible for symmetric key generation key
a SecretKey DESKey keygen.generateKey = ();
// generating a Cipher object, specify its support AES algorithm, the encryption or decryption Cipher responsible for completing the work
C = Cipher.getInstance cipher ( "the AES");
// The key, cipher object is initialized, denotes decryption mode DECRYPT_MODE
c.init (Cipher.DECRYPT_MODE, DESKey);
// save the byte array is responsible result of the decryption, the decryption Base64 str, firstly, the hex conversion to binary
byte [] cipherByte = c.doFinal (HexConvertUtil.parseHexStr2Byte ( Base64ConvertUtil.decode (STR)));
return new new String (cipherByte);
} the catch (NoSuchAlgorithmException | a NoSuchPaddingException E) {
logger.error ( "the getInstance () method exception:" + e.getMessage ());
the throw new new CustomUnauthorizedException ( " getInstance () method exception: "+ e.getMessage ());
} the catch (UnsupportedEncodingException E) {
logger.error (" the Base64 decryption exception: "+ e.getMessage ());
the throw new new CustomUnauthorizedException (" exception decrypt the Base64: " + e.getMessage ());
} catch (InvalidKeyException e) {
logger.error ( "Cipher object is initialized Exception:" + e.getMessage ());
the throw new new CustomUnauthorizedException ( "Cipher object is initialized Exception:" + e.getMessage ());
} the catch (IllegalBlockSizeException | BadPaddingException E) {
logger.error ( "abnormal decryption key error:" + e.getMessage ());
the throw new new CustomUnauthorizedException ( "abnormal decryption key error:" + e.getMessage ());
}
}
}
/ ** 
* the JWT the JAVA-based tools
* /
@Component
public class JwtUtil {

/ **
* Logger
* /
Private static Logger Logger = Final LoggerFactory.getLogger (JwtUtil.class);

/ **
* expiration time is changed from the configuration file Get
* /
Private static String accessTokenExpireTime;

/ **
* the JWT authentication private key encryption (the Base64 encryption)
* /
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 decrypted authentication UnsupportedEncodingException exception occurs:" + e.getMessage ());
the throw new new customException ( "JWTToken decrypted authentication UnsupportedEncodingException exception occurs:" + e.getMessage ());
}
}

/ **
* obtained Token decrypting the secret information can be obtained without
* /
public static String getClaim (String token, the Claim String) {
the try {
DecodedJWT JWT = JWT.decode (token);
// String only output type, if other types of return null
return jwt.getClaim (the Claim) .asString ();
} the catch (JWTDecodeException E) {
logger.error ( "public decrypted information Token appearances JWTDecodeException exception:" + e.getMessage ());
throw new CustomException ( "Public decrypted information Token JWTDecodeException abnormal appearances:" + e.getMessage ());
}
}

/ **
* generates signature
* /
public static String Sign (Account String, String with currentTimeMillis) {
the try {
// JWT private key encryption plus account
String account + Secret = Base64ConvertUtil.decode (encryptJWTKey);
// where the expiration time is in milliseconds, it is multiplied by 1000
a Date = new new DATE a Date (System.currentTimeMillis () + Long.parseLong ( accessTokenExpireTime) * 1000);
Mathimatics-Numerical algorithms algorithm = Algorithm.HMAC256 (Secret);
// incidental account account information
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());
}
}
}

/ **
* Get the current logged on user tools
* /
@Component
public class UserUtil {

Private Final UsersMapper UserMapper;

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

/ **
* Get the current logged in user
* @param
* /
public UsersDto the getUser () {
String token = SecurityUtils.getSubject () getPrincipal () toString ();..
// obtained by decrypting the Account
String Account = JwtUtil.getClaim (token, Constant.ACCOUNT);
UsersDto usersDto new new UsersDto = ( );
usersDto.setAccount (Account);
usersDto = userMapper.selectOne (usersDto);
// user exists
IF (usersDto == null) {
the throw new new customException ( "The account does not exist (at The the Account does not exist).");
}
Return usersDto;
}

/ **
* Get the current logged-on user Id
* @param
* /
public getUserId Integer () {
return the getUser () getId ();.
}

/ **
* Get the current logged in user the Token
* @param
* /
public String getToken to () {
return SecurityUtils.getSubject () getPrincipal () toString.. ();
}

/ **
* Get the current login user the Account
* /
public String the getAccount () {
String token = SecurityUtils.getSubject().getPrincipal().toString();
// 解密获得Account
return JwtUtil.getClaim(token, Constant.ACCOUNT);
}
}

Guess you like

Origin www.cnblogs.com/Treesir/p/11600245.html