<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
import org.apache.commons.codec.binary.Base64;
public class AESUtil {
// 加密
public static String Encrypt(String sSrc, String sKey) {
try {
log.info("加密前封包:{}",sSrc);
if (checkParam(sKey)) return null;
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"));
String str = new Base64().encodeToString(encrypted);//此處使用BASE64做轉碼功能,同時能起到2次加密的作用。
log.info("加密後封包:{}",str);
return str;
} catch (Exception e) {
log.error("加密失敗:{}", e);
}
return null;
}
// 解密
public static String Decrypt(String sSrc, String sKey) {
try {
log.info("解密前封包:{}",sSrc);
// 判斷Key是否正确
if (checkParam(sKey)) return null;
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);
byte[] original = cipher.doFinal(new Base64().decode(sSrc));
String originalString = new String(original, "utf-8");
log.info("解密後封包:{}",originalString);
return originalString;
} catch (Exception e) {
log.info("解密失敗,error:{}", e);
}
return null;
}
public static boolean checkParam(String sKey) {
if (sKey == null) {
log.error("Key為空");
return true;
}
// 判斷Key是否為16位
if (sKey.length() != 16) {
log.error("Key長度不是16位");
return true;
}
return false;
}
public static String encrypt(JsonResult jsonResult) {
String str = AESUtil.Encrypt(Json.toString(jsonResult), Constant.KEY);
return str;
}
}