package utils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/***
*@author lixianbin
*@desc
*@date created in 2021/7/6
**/
public class AESUtil {
/**
* AES加密
* @param sSrc
* @param sKey
* @return
*/
public static String Encrypt(String sSrc, String sKey){
try {
byte[] raw = sKey.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
//"算法/模式/补码方式"
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
//此处使用BASE64做转码功能,同时能起到2次加密的作用。
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* AES解密
* @param sSrc
* @param sKey
* @return
*/
public static String AESDecrypt(String sSrc, String sKey) {
try {
byte[] raw = sKey.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
//先用base64解密
byte[] encrypted1 = Base64.getDecoder().decode(sSrc);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "UTF-8");
return originalString;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}