Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 SQLCipher 為 Android 的 SQLite 資料庫加密

編輯:關於 Android 程式設計

原生的 SQLite 資料庫是完全沒有加密的,任何人只要把 /data/data/<package>/databases/ 下的檔案拉出來,用任意 SQLite 工具就能看光所有內容。SQLCipher 是目前 Android 上最主流的解法,它在 SQLite 與檔案系統之間插入一層 AES 加密。

接入步驟

  1. 把 SQLCipher 的 jar 放進專案的 libs 目錄。
  2. 把 libs/armeabi(以及 armeabi-v7a、x86 等)下的 .so 原生庫一併放進去。
  3. 程式碼中的 import 必須全部換成 net.sqlcipher.* 底下,而不是 android.database.*。

建立加密資料庫的 Helper

public class SQLCipherOpenHelper extends SQLiteOpenHelper {

    private final static String DATABASE_NAME = "test.db";

    public SQLCipherOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table person(personid integer primary key autoincrement,"
                + "name varchar(20), phone VARCHAR(12))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

注意 import 來源:

import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;

初始化與使用

private final String SECRET_KEY = "95279527";

private void initDataBase() {
    // 1. 載入 libs 下的 so 原生庫
    SQLiteDatabase.loadLibs(this);
    // 2. 取得 Helper
    mSqlCipherOpenHelper = new SQLCipherOpenHelper(this);
    // 3. 帶著密碼開啟(或建立)資料庫
    mSqLiteDatabase = mSqlCipherOpenHelper.getWritableDatabase(SECRET_KEY);
}

寫入用參數綁定,避免 SQL 注入:

public void addData(Person person) {
    mSqLiteDatabase.execSQL("insert into person (name, phone) values(?, ?)",
            new Object[] { person.getName(), person.getPhone() });
}

查詢時必須使用 SQLCipher 自己的 Cursor:

import net.sqlcipher.Cursor;

public Person queryData(int id) {
    Cursor cursor = mSqLiteDatabase.rawQuery(
            "select * from person where personid=?",
            new String[] { String.valueOf(id) });
    while (cursor.moveToFirst()) {
        int personid = cursor.getInt(cursor.getColumnIndex("personid"));
        String name  = cursor.getString(cursor.getColumnIndex("name"));
        String phone = cursor.getString(cursor.getColumnIndex("phone"));
        return new Person(personid, name, phone);
    }
    cursor.close();
    return null;
}

幾個務實的提醒

  • loadLibs() 必須在任何資料庫操作之前呼叫,而且整個 App 生命週期只需呼叫一次。
  • 密碼不能寫死在原始碼裡。示例中的 SECRET_KEY 只是為了示範。正式專案應該把金鑰存放於 Android Keystore,或由使用者輸入,並且不落磁碟。
  • ABI 要齊全。缺少對應 CPU 架構的 .so,在該架構的裝置上會直接 UnsatisfiedLinkError。建議用 abiFilters 明確宣告支援範圍。
  • 效能有代價。每次頁面操作都要解密,大量查詢時會明顯變慢。只加密真正敏感的表,是比較務實的取捨。
  • APK 體積會增加數 MB,這是把原生庫打包進去的必然結果。
  • 若只是要保護少量設定資料,EncryptedSharedPreferences(Jetpack Security)會是更輕的選擇。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved