編輯:關於 Android 程式設計
AES 是最常用的對稱式加密演算法。本文提供一個可直接複用的 Android AES 加解密工具類,並說明加密字串組成的觀念。
一個完整的加密方案由「演算法 + 模式 + 填充」組成。Java 不支援 PKCS7Padding,只支援 PKCS5Padding,因此本文使用 AES/ECB/PKCS5Padding。
要注意 ECB 模式相同明文會產生相同密文,安全性較弱,正式專案建議改用 AES/CBC/PKCS5Padding 並搭配隨機 IV;若要做跨 iOS 與 Android 通用的方案,雙方的模式與填充必須完全一致。
package com.example.aesdemo;
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/** AES 對稱加密解密類 **/
public class AESHelper {
/** 演算法/模式/填充 **/
private static final String CipherMode = "AES/ECB/PKCS5Padding";
/** 建立金鑰:不足 32 位元補 0,超出則截斷 **/
private static SecretKeySpec createKey(String password) {
byte[] data = null;
if (password == null) {
password = "";
}
StringBuffer sb = new StringBuffer(32);
sb.append(password);
while (sb.length() < 32) {
sb.append("0");
}
if (sb.length() > 32) {
sb.setLength(32);
}
try {
data = sb.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new SecretKeySpec(data, "AES");
}
/** 加密位元組資料 **/
public static byte[] encrypt(byte[] content, String password) {
try {
SecretKeySpec key = createKey(password);
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(content);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/** 加密(結果為 16 進位字串) **/
public static String encrypt(String content, String password) {
byte[] data = null;
try {
data = content.getBytes("UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
data = encrypt(data, password);
return byte2hex(data);
}
/** 解密位元組陣列 **/
public static byte[] decrypt(byte[] content, String password) {
try {
SecretKeySpec key = createKey(password);
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(content);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/** 將 16 進位字串解密為字串 **/
public static String decrypt(String content, String password) {
byte[] data = null;
try {
data = hex2byte(content);
} catch (Exception e) {
e.printStackTrace();
}
data = decrypt(data, password);
if (data == null) return null;
try {
return new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/** 位元組陣列轉 16 進位字串 **/
public static String byte2hex(byte[] b) {
StringBuffer sb = new StringBuffer(b.length * 2);
String tmp = "";
for (int n = 0; n < b.length; n++) {
tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
}
return sb.toString().toUpperCase();
}
/** 將 hex 字串轉換成位元組陣列 **/
private static byte[] hex2byte(String inputString) {
if (inputString == null || inputString.length() < 2) {
return new byte[0];
}
inputString = inputString.toLowerCase();
int l = inputString.length() / 2;
byte[] result = new byte[l];
for (int i = 0; i < l; ++i) {
String tmp = inputString.substring(2 * i, 2 * i + 2);
result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
}
return result;
}
}
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String masterPassword = "a";
String originalText = "於";
try {
String encryptingCode = AESHelper.encrypt(originalText, masterPassword);
Log.i("加密結果為 ", encryptingCode);
String decryptingCode = AESHelper.decrypt(encryptingCode, masterPassword);
Log.i("解密結果", decryptingCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
09-19 10:41:05.467: I/加密結果為(707): E55C24701F6380478E1940ADDFD08D22 09-19 10:41:05.467: I/解密結果(707): 於
這個類別把金鑰直接由密碼字串補零而來,方便示範但不適合正式環境:金鑰若硬編碼在 APK 中,反編譯後即可輕易取得。實務上應改用 Android Keystore 產生並保存金鑰,或以 PBKDF2 從使用者密碼衍生的金鑰,並搭配 CBC 模式與隨機 IV。另外,若加解密過程發生任何例外,doFinal 都會失敗,此時工具類回傳 null,呼叫端務必做 null 判斷,避免後續 byte2hex 收到 null 而拋出 NullPointerException。
Android 自訂 Tab 式選單(TabMenu)實作教學
用過 UCWEB Android 版的人,大概都對它那個特殊的選單有印象:把選單做成帶分頁的 Tab 形式,能容納比 Android 傳統選單更豐富的內容(系統選單超過
從零實現下拉刷新:Android RefreshLayout 自定義手勢佈局全解析
專案裡需要下拉刷新功能,但目標 View 並不是 ListView 這類現成控件,而是普通 ViewGroup,需要自己實現。網上翻了半天沒找到特別合適、又看得懂的方案,
Android 仿餓了麼加入購物車的伸縮旋轉按鈕
這個效果以純自定義 View 實作,不依賴多層 ViewGroup 組合。它可以在數量為 0 時顯示提示文字,點擊後展開加號與減號,並在增減數量時播放旋轉、位移與透明
Android 中使用 RecyclerView 實現下拉刷新和上拉加載
為 RecyclerView 實作下拉刷新與上拉加載,可以善用成熟開源庫,而不必從零打造手勢與動畫。常見方案是使用 Ultra-Pull-To-Refresh 提供的 P