直接上代码:
public class AESUtil {
static final String algorithmStr = "AES/ECB/PKCS5Padding";
private static final Object TAG = "AES";
static private KeyGenerator keyGen;
static private Cipher cipher;
static boolean isInited = false;
private static void init() {
try {
keyGen = KeyGenerator.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 初始化此密钥生成器,使其具有确定的密钥长度。
keyGen.init(128); //128位的AES加密
try {
// 生成一个实现指定转换的 Cipher 对象。
cipher = Cipher.getInstance(algorithmStr);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
//标识已经初始化过了的字段
isInited = true;
}
private static byte[] genKey() {
if (!isInited) {
init();
}
//首先 生成一个密钥(SecretKey),
//然后,通过这个秘钥,返回基本编码格式的密钥,如果此密钥不支持编码,则返回 null。
return keyGen.generateKey().getEncoded();
}
private static byte[] encrypt(byte[] content, byte[] keyBytes) {
byte[] e