public class EncodingUtil {
//AES加密
private static final String KEY = "yflyyflyyflyyfly";
/**
* 接收一个字符串,用md5加密
*/
public static byte[] md5Encoding(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(str.getBytes());
return digest;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 接收手机号和密码,用md5加密
*/
public static String psdEncoding(String password, String phone) {
byte[] md5Encoding = md5Encoding(password+phone);
return new BigInteger(md5Encoding).toString(16);
}
/**
* 接收字符串,AES加密
*/
public static String aesEncoding(String msg) {
if(msg == null) {
throw new RuntimeException("加密字符串不能为空");
}
try {
Cipher cipher = Cipher.getInstance("AES");//根据算法名称/工作模式/填充模式获取Cipher实例
Key key = new SecretKeySpec(KEY.getBytes(), "AES");//根据算法名称初始化一个SecretKey实例,密钥必须是指定长度;
cipher.init(Cipher.ENCRYPT_MODE, key);//使用SerectKey初始化Cipher实例,并设置加密或解密模式;
byte[] endata = cipher.doFinal(msg.getBytes());//传入明文或密文,获得密文或明文
return Base64.getEncoder().encodeToString(endata);//最后使用base64加密,返回字符串
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("加密失败");
}
}
/**
* AES解密
* 接收base64加密后的字符串
* 先base64解密
* 再AES解密
*/
public static String aesDeCoding(String bs64Str) {
if(bs64Str == null) {
throw new RuntimeException("解密字符串不能为空");
}
try {
Cipher cipher = Cipher.getInstance("AES");
Key key = new SecretKeySpec(KEY.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] code = Base64.getDecoder().decode(bs64Str);
byte[] dedata = cipher.doFinal(code);
return new String(dedata);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("加密失败");
}
}
}