public class AesUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(AesUtils.class);
private static final String ENCODING = "UTF-8";
private static final String AES_ALGORITHM = "AES";
private static final String CIPHER_PADDING = "AES/ECB/NoPadding";
private static final String CIPHER_CBC_PADDING = "AES/CBC/NoPadding";
private static final String IV_SEED = "1234567812345678";
public static byte[] encrypt(byte[] content, String aesKey) {
if (content == null || content.length == 0) {
LOGGER.info("AES encrypt: the content is null!");
return null;
}
int n = content.length / 16 + 1;
byte[] result = new byte[16 * n];
System.arraycopy(content, 0, result, 0, content.length);
for (int i = content.length; i < result.length; i++) {
result[i] = 0x00;
}
if (StringUtils.isNotBlank(aesKey)) {
try {
byte[] bytes = HexUtils.hexToByteArray(aesKey);
if (bytes.length != 16) {
throw new RuntimeException("AES length error");
}
SecretKeySpec skeySpec = new SecretKeySpec(bytes, AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_PADDING);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(result);
return encrypted;
} catch (Exception e) {
LOGGER.info("AES encrypt exception:" + e.getMessage());
throw new RuntimeException(e);
}
} else {
LOGGER.info("AES encrypt: the aesKey is null or error!");
return null;
}
}
public static byte[] decrypt(byte[] content, String aesKey) {
if (content == null || content.length == 0) {
LOGGER.info("AES decrypt: the content is null!");
return null;
}
if (StringUtils.isNotBlank(aesKey)) {
try {
byte[] bytes = HexUtils.hexToByteArray(aesKey);
if (bytes.length != 16) {
throw new RuntimeException("AES length error");
}
SecretKeySpec skeySpec = new SecretKeySpec(bytes, AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_PADDING);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(content);
return decrypted;
} catch (Exception e) {
LOGGER.info("AES decrypt exception:" + e.getMessage());
throw new RuntimeException(e);
}
} else {
LOGGER.info("AES decrypt: the aesKey is null or error!");
return null;
}
}
}
Like (0)
Donate
微信扫一扫
支付宝扫一扫

