Java AES 加密工具
package com.springboot.demo;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class EncryptUtil {
private static final String KEY_ALGORITHM = "AES";
/** 算法/模式/补码方式 */
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
public static byte[] encrypt2bytes(byte[] contents, byte[] secretKey) {
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(contents);
} catch (Exception e) {
return null;
}
}
public static byte[] decrypt(byte[] contents, byte[] secretKey) throws Exception {
if (secretKey == null) {
return null;
}
SecretKeySpec keySpec = new SecretKeySpec(secretKey, KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
try {
return cipher.doFinal(contents);
} catch (Exception e) {
return null;
}
}
}