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

詳解 Android 資料儲存之 SQLCipher 資料庫加密

編輯:關於 Android 程式設計

Android 的 SQLite 資料庫預設存放在應用程式目錄下。若裝置已 root,資料庫檔案可能被存取,因此對敏感資料進行加密是必要的。SQLCipher 是在 SQLite 基礎上擴充的開源加密資料庫方案,適合行動裝置使用。

為何選擇 SQLCipher

  • 加密開銷較低。
  • 可做到資料庫層級加密。
  • 使用方式與原生 SQLite 相近。
  • 適合需要保護本機資料的 App。

加入依賴

dependencies {
    compile 'net.zetetic:android-database-sqlcipher:3.4.0'
}

建立 SQLiteOpenHelper

使用 SQLCipher 時,所有 SQLite 相關類別都要改為引用 net.sqlcipher.database。

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

public class DBCipherHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "test_cipher_db";
    public static final String DB_PWD = "whoislcj";
    public static final String TABLE_NAME = "person";
    public static final String FIELD_ID = "id";
    public static final String FIELD_NAME = "name";

    public DBCipherHelper(Context context) {
        super(context, DB_NAME, null, 1);
        SQLiteDatabase.loadLibs(context);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE " + TABLE_NAME + " ("
                + FIELD_ID + " integer primary key autoincrement, "
                + FIELD_NAME + " text not null);";
        db.execSQL(sql);
    }

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

請注意:SQLiteDatabase.loadLibs(context) 不可省略,否則會無法正確載入加密相關函式庫。

取得加密資料庫

傳統 SQLite 取得資料庫的方式如下:

SQLiteDatabase db = dbHelper.getWritableDatabase();

SQLCipher 則需要傳入密碼:

SQLiteDatabase db = dbHelper.getWritableDatabase(DBCipherHelper.DB_PWD);
SQLiteDatabase readableDb = dbHelper.getReadableDatabase(DBCipherHelper.DB_PWD);

基本操作

插入資料:

ContentValues cv = new ContentValues();
cv.put(DBCipherHelper.FIELD_NAME, name);
db.insert(DBCipherHelper.TABLE_NAME, null, cv);

查詢資料:

Cursor cursor = db.query(
        DBCipherHelper.TABLE_NAME,
        new String[]{DBCipherHelper.FIELD_NAME},
        null, null, null, null, null);

while (cursor.moveToNext()) {
    String name = cursor.getString(0);
}

事務支援

SQLCipher 也支援傳統 SQLite 的事務寫法:

db.beginTransaction();
try {
    db.insert(DBCipherHelper.TABLE_NAME, null, cv);
    db.setTransactionSuccessful();
} finally {
    db.endTransaction();
}

透過 SQLCipher,可以在不改變太多既有 SQLite 使用習慣的情況下,為本機資料庫加上一層加密保護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved