此处密码模式为:AES/ECB/PKCS5Padding
public class AESUtil {
static final String algorithmStr = "AES/ECB/PKCS5Padding";
private static final Object TAG = "AES";
private static final String PWD = "aaa";//(此处密码不是随机生成,是后台生成规定好)
public static String encryptToBase64(String data){
try {
if (!TextUtils.isEmpty(data)) {
byte[] valueByte = encrypt(data.getBytes("UTF-8"), PWD.getBytes("UTF-8"));
return encodeBase64(valueByte);
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static byte[] encrypt(byte[] data, byte[] key) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance(algorithmStr);
cipher.init(Cipher.ENCRYPT_MODE, seckey);
byte[] result = cipher.doFinal(data);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String encodeBase64(byte[] input) {
try {
return new String(Base64.encodeToString(input,Base64.NO_WRAP));
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}