import?org.apache.commons.lang3.StringUtils;
import?org.slf4j.Logger;
import?org.slf4j.LoggerFactory;
import?javax.crypto.Cipher;
import?javax.crypto.spec.SecretKeySpec;
public?class?AESUtil?{
public?static?final?Logger?LOGGER?=?LoggerFactory.getLogger(AESUtil.class);
public?static?final?String?ENCRYPTED_KEY?=?"<TEST>KEY,123";
/**
*? *?@param?sSrc *?@param?sKey *?@return *?@throws?Exception */public?static?String?encrypt(String?sSrc,?String?sKey)?throws?Exception?{
//判斷加密串是否為空,長度是否為16
if?(StringUtils.isBlank(sKey)?||?sKey.length()?!=?16)?{
LOGGER.error("sKey為空null或長度不是16");
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"));
return?new?String(new?Base64().encode(encrypted),"UTF-8");
}
/**
*? *?@param?enString *?@param?sKey *?@return *?@throws?Exception */public?static?String?decrypt(String?enString,?String?sKey)?throws?Exception?{
try?{
if?(StringUtils.isBlank(sKey)?||?sKey.length()?!=?16)?{
LOGGER.error("sKey為空null或長度不是16");
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[]?encrypted1?=?(byte[])?new?Base64().decode(enString.getBytes());
try?{
byte[]?original?=?cipher.doFinal(encrypted1);
String?originalString?=?new?String(original,"utf-8");
return?originalString;
}?catch?(Exception?e)?{
LOGGER.error(e.toString());
return?null;
}
}?catch?(Exception?ex)?{
LOGGER.error(ex.toString());
return?null;
}
}
}