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.isEmpty(iv)) {
ivByte = create128BitsIV(iv).getBytes("UTF-8");
}
byte[] result = decryptAES(strByte, keyByte, transformation, ivByte);
return new String(result, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static String encryptAES2Hex(String content, String key, String transformation, String iv) {
key = create128BitsKey(key);
try {
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);
if (result != null) return bytesToHexString(result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static String decryptHexAES(String hexStr, String key, String transformation, String iv) {
key = create128BitsKey(key);
try {
byte[] strByte = hexStringToBytes(hexStr);
byte[] keyByte = key.getBytes("UTF-8");
byte[] ivByte = null;
if (!TextUtils.isEmpty(iv)) {
ivByte = create128BitsIV(iv).getBytes("UTF-8");
}
byte[] result = decryptAES(strByte, keyByte, transformation, ivByte);
return new String(result, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
private static String create128BitsKey(String key) {
if (key == null || key.length() != 16) {
throw new RuntimeException("Unsupported key size,秘钥长度必须为16字节");
}
StringBuffer buffer = new StringBuffer(16);
buffer.append(key);
while (buffer.length() < 16) {
buffer.append("0");
}
if (buffer.length() > 16) {
buffer.setLength(16);
}
return buffer.toString();
}
private static String create128BitsIV(String iv) {
if (iv == null || iv.length() != 16) {
throw new RuntimeException("Unsupported iv size,iv长度必须为16字节");
}
StringBuffer buffer = new StringBuffer(16);
buffer.append(iv);
while (buffer.length() < 16) {
buffer.append("0");
}
if (buffer.length() > 16) {
buffer.setLength(16);
}
return buffer.toString();
}
public static byte[] encryptAES(byte[] content, byte[] keyBytes, String transformation, byte[] iv) {
return encrypt(content, keyBytes, Algorithm_AES, transformation, iv);
}
public static byte[] encryptDES(byte[] content, byte[] keyBytes, String transformation, byte[] iv) {
return encrypt(content, keyBytes, Algorithm_DES, transformation, iv);
}
public static byte[] encrypt(byte[] content, byte[] keyBytes, String algorithm, String transformation, byte[] iv) {
try {
SecretKey key;
if (Algorithm_DES.equals(algorithm)) {
DESKeySpec desKey = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
key = keyFactory.generateSecret(desKey);
} else {
key = new SecretKeySpec(keyBytes, algorithm);
}
Cipher cipher;
if (iv == null || iv.length == 0) {
cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.ENCRYPT_MODE, key);
} else {
cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
}
return cipher.doFinal(content);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public static byte[] decryptAES(byte[] content, byte[] keyBytes, String transformation, byte[] iv) {
return decrypt(content, keyBytes, Algorithm_AES, transformation, iv);
}
public static byte[] decryptDES(byte[] content, byte[] keyBytes, String transformation, byte[] iv) {
return decrypt(content, keyBytes, Algorithm_DES, transformation, iv);
}
public static byte[] decrypt(byte[] content, byte[] keyBytes, String algorithm, String transformation, byte[] iv) {
try {
SecretKey key;
if (Algorithm_DES.equals(algorithm)) {
DESKeySpec desKey = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
key = keyFactory.generateSecret(desKey);
} else {
key = new SecretKeySpec(keyBytes, algorithm);
}
Cipher cipher;
if (iv == null || iv.length == 0) {
cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, key);
} else {
cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
}
return cipher.doFinal(content);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = null;
int sdk_version = android.os.Build.VERSION.SDK_INT;
if (sdk_version > 23) {
sr = SecureRandom.getInstance("SHA1PRNG", new CryptoProvider());
} else if (sdk_version >= 17) {
sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
} else {
sr = SecureRandom.getInstance("SHA1PRNG");
}
sr.setSeed(seed);
kgen.init(128, sr);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static byte[] hexStringToBytes(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static int toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
public static final String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
16);
result[i] = (byte) (high * 16 + low);
}
return result;
}