編輯:關於 Android 開發
AES 是一種對稱可逆加密算法,非常適合用來保護用戶的敏感信息。實務上常見的做法是:先用 AES 對原始數據加密,再對密文做一次 Base64 編碼,讓結果可以安全地以文本形式傳輸或落庫。
下面是一個可直接複用的工具類實現,採用 AES/CBC/PKCS5Padding 模式:
/**
* AES 是一種可逆加密算法,用於對用戶的敏感信息加密處理。
* 對原始數據進行 AES 加密後,再進行 Base64 編碼轉化。
*/
public class AESOperator {
/*
* 加密用的 Key,可由 26 個字母和數字組成。
* 此處使用 AES-128-CBC 加密模式,key 需要為 16 位。
*/
private String sKey = "10d2Xd4hf0s1XvSw";
private String ivParameter = "10d2Xd4hf0s1XvSw";
private static AESOperator instance = null;
private AESOperator() {
}
public static AESOperator getInstance() {
if (instance == null) {
instance = new AESOperator();
}
return instance;
}
public static String Encrypt(String encData, String secretKey, String vector)
throws Exception {
if (secretKey == null || secretKey.length() != 16) {
return null;
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = secretKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// 使用 CBC 模式需要一個向量 iv,可增加加密算法的強度
IvParameterSpec iv = new IvParameterSpec(vector.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
// 此處使用 BASE64 轉碼
return new BASE64Encoder().encode(encrypted);
}
// 加密
public String encrypt(String sSrc) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
return new BASE64Encoder().encode(encrypted);
}
// 解密
public String decrypt(String sSrc) throws Exception {
try {
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
// 先進行 base64 解碼
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
byte[] original = cipher.doFinal(encrypted1);
return new String(original, "utf-8");
} catch (Exception ex) {
return null;
}
}
public String decrypt(String sSrc, String key, String ivs) throws Exception {
try {
byte[] raw = key.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
byte[] original = cipher.doFinal(encrypted1);
return new String(original, "utf-8");
} catch (Exception ex) {
return null;
}
}
public String decryptOrRaw(String sSrc) throws Exception {
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(sSrc.getBytes("utf-8"));
return new String(original, "utf-8");
}
}
AES 支持 128、192、256 三種密鑰長度,對應的位元組數分別是 16、24、32。代碼中之所以反覆校驗 secretKey.length() != 16,就是因為這裡固定走的是 AES-128。如果傳入的 key 長度不對,Cipher.init() 會直接拋出 InvalidKeyException。
AES 加密的輸出是任意字節序列,其中包含大量不可打印字符,無法直接放進 JSON、URL 或文本數據庫字段。Base64 把二進制映射為 64 個可打印字符,解決了「密文如何以文本形式承載」的問題。注意 Base64 只是編碼而非加密,不能單獨作為安全手段。
示例中的 sKey 與 ivParameter 直接寫死在源碼中,僅便於演示。這樣做存在明顯風險:APK 可以被反編譯,常量池中的字符串一眼可見,等於加密形同虛設。實戰中更推薦的做法包括:
catch 之後的 return null解密方法在異常時返回 null,調用方必須做空值判斷,否則容易在鏈路上引發 NullPointerException。更嚴謹的做法是拋出受檢異常或返回明確的錯誤結果對象,讓問題尽早暴露。
示例使用了 BASE64Encoder / BASE64Decoder(早期的 sun.misc 或第三方實現)。在 Android 上更推薦直接使用 android.util.Base64.encodeToString() 與 decode(),並顯式指定 Base64.NO_WRAP 避免插入換行符導致密文比對失敗。
用 Gallery 與 ImageSwitcher 打造可左右無限循環的圖片瀏覽器
用 Gallery 與 ImageSwitcher 打造可左右無限循環的圖片瀏覽器 製作圖片瀏覽器時,若能實現左右無限循環滑動,使用者體驗會大幅提升。要達成這個效果,關
Android 開發實戰(十四):用 Logcat 監聽系統日誌,破解定制 ROM 的授權難題
這一節分享一個在 App 裡「反過來監聽 Logcat」的實用技巧。乍聽有點繞,但它解決的是一個非常真實的工程問題。 問題從哪裡來:定制系統讓適配變成噩夢 Androi
Android 開源庫與項目推薦(二):帶尾巴的 RecyclerViewPager
Android 開源庫與項目推薦(二):帶尾巴的 RecyclerViewPager 1、帶尾巴的 RecyclerViewPager 它的特點包括: 1、像 ViewP
Android PendingIntent 詳解:通知、短信與延遲 Intent
Android PendingIntent 詳解:通知、短信與延遲 Intent PendingIntent 可以理解為一個等待被觸發的 Intent。它與一般 Inte