import android.text.TextUtils;
import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* describe: AES加密算法
*/
public class AesUtils {
/**
* 加密
*/
public static String Encrypt(String text) {
if (TextUtils.isEmpty(text)) {
return text;
}
try {
byte[] result = encrypt("your key", text);
return new String(Base64.encode(result, Base64.DEFAULT));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*解密
*/
public static String Decrypt(String text) {
try {
byte[] result = decrypt(Base64.decode(text, Base64.DEFAULT), "your key")
return new String(result);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static byte[] encrypt(String key, String text) throws Exception {
// 创建AES秘钥
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
// 初始化加密器
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// 加密
return cipher.doFinal(text.getBytes("UTF-8"));
}
private static byte[] decrypt(byte[] content, String key) throws Exception {
// 创建AES秘钥
SecretKeySpec key = new SecretKeySpec(key.getBytes(), "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
// 初始化解密器
cipher.init(Cipher.DECRYPT_MODE, key);
// 解密
return cipher.doFinal(content);
}
}
Android AES 加密解密
未经允许不得转载:工具盒子 » Android AES 加密解密