AES加密工具 之前有些坑在里面,现在整理一下,条理清晰点
import android.text.TextUtils;
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Provider;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESUtils {
private static final String Algorithm_AES = "AES";
private static final String Algorithm_DES = "DES";
private static final String CipherMode_CBC_PKCS5 = "AES/CBC/PKCS5Padding";
private static final String CipherMode_ECB_PKCS5 = "AES/ECB/PKCS5Padding";
private static final String CipherMode_CBC_PKCS7 = "AES/CBC/PKCS7Padding";
private static final String CipherMode_ECB_PKCS7 = "AES/ECB/PKCS7Padding";
public static String encryptAES_ECB7_2Base64(String contentStr, String key) {
return encryptAES2Base64(contentStr, key, CipherMode_ECB_PKCS7, null);
}
public static String decryptBase64AES_ECB7(String base64Str, String key) {
return decryptBase64AES(base64Str, key, CipherMode_ECB_PKCS7, null);
}
public static String encryptAES2Base64(String content, String key, String transformation, String iv) {
if (TextUtils.isEmpty(content)) return "";
try {
key = create128BitsKey(key);
byte[] strByte = content.getBytes("UTF-8");
byte[] keyByte = key.getBytes("UTF-8");
byte[] ivByte = null;
if (!TextUtils.isEmpty(iv)) {
ivByte = create128BitsIV(iv).getBytes("UTF-8");
}
byte[] result = encryptAES(strByte, keyByte, transformation, ivByte);
return Base64.encodeToString(result, Base64.NO_WRAP);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static String decryptBase64AES(String base64Str, String key, String transformation, String iv) {
if (TextUtils.isEmpty(base64Str)) return "";
try {
key = create128BitsKey(key);
byte[] strByte = Base64.decode(base64Str, Base64.NO_WRAP);
byte[] keyByte = key.getBytes("UTF-8");
byte[] ivByte = null;
if (!TextUtils.