基于Sqlcipher和GreenDao的数据库加密

由于需要修改源码,所以无法再通过compile 'de.greenrobot:greendao:2.0.0'来引入依赖库,下载GreenDao代码:

git clone https://github.com/greenrobot/greenDAO.git

只需要DaoCore部分即可,并且可以删除de.greenrobot.dao.test包和de.greenrobot.dao.InternalUnitTestDaoAccess.java

主要需要做如下修改:

1. android.database.sqlite.SQLiteDatabase 改为: net.sqlcipher.database.SQLiteDatabase

2. android.database.sqlite.SQLiteStatement 改为: net.sqlcipher.database.SQLiteStatement

3. android.database.DatabaseUtils 改为: net.sqlcipher.DatabaseUtils

4. de.greenrobot.dao.internal.FastCursor增加实现方法:

    @Override
    public void setExtras(Bundle extras) {
    }

由于修改量不大,对于DaoGenerator部分暂时没有研究,以后有时间再做研究,本人目前使用的是AndroidAnnotations还没有升级到butterknife,所以本次还是暂时使用它。

项目的build.gradle修改如下:

classpath 'com.android.tools.build:gradle:1.5.0'

classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' // 新增


在module的buid.gradle修改内容如下:

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt' // 新增

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "org.penguin.study.android.sqlciphertest"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.*'])
    compile 'com.android.support:appcompat-v7:23.1.1'
    apt 'org.androidannotations:androidannotations:3.3.2'
    compile 'org.androidannotations:androidannotations-api:3.3.2'
}
apt {
    arguments {
        resourcePackageName android.defaultConfig.applicationId
        androidManifestFile variant.outputs[0]?.processResources?.manifestFile
    }
}


创建Dao工具类:

package org.penguin.study.android.sqlciphertest.util;

import android.content.Context;
import net.sqlcipher.database.SQLiteDatabase;

import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import org.penguin.study.android.sqlciphertest.dao.BookDao;
import org.penguin.study.android.sqlciphertest.dao.DaoMaster;
import org.penguin.study.android.sqlciphertest.dao.DaoSession;

@EBean(scope = EBean.Scope.Singleton)
public class DAOBean {

    static final String TAG = DAOBean.class.getSimpleName();
    public static final String DATABASE_NAME = "demo-db";
    static final String secretKey = "Your Secret Key";

    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;

    private BookDao bookDao;

    @RootContext
    Context context;
    
    public DaoSession getDaoSession() {
        if (daoSession == null) {
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DATABASE_NAME, null);
            db = helper.getWritableDatabase(secretKey);
            daoMaster = new DaoMaster(db);
            daoSession = daoMaster.newSession();

        }
        return daoSession;
    }

    public BookDao getBookDao() {
        if (bookDao == null) {
            bookDao = getDaoSession().getBookDao();
        }
        return bookDao;
    }
}

具体使用:

package org.penguin.study.android.sqlciphertest;

import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.penguin.study.android.sqlciphertest.dao.BookDao;
import org.penguin.study.android.sqlciphertest.model.Book;
import org.penguin.study.android.sqlciphertest.util.DAOBean;

import java.util.List;

@EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.class.getSimpleName();

    private BookDao bookDao;

    @Bean
    DAOBean daoBean;

    private synchronized BookDao getBookDao() {
        if (bookDao == null) {
            bookDao = daoBean.getBookDao();
        }
        return bookDao;
    }

    @Click(R.id.add_data)
    void clickedAddDataButton() {
        Book newBook = new Book();
        newBook.setName("射雕英雄传");
        newBook.setDescription("金庸先生的经典著作!");
        newBook.setPages(1241);
        newBook.setPrice(178.0);
        getBookDao().insertOrReplace(newBook);
        shortToast("成功添加图书记录。");
    }

    @Click(R.id.query_data)
    void clickedQueryDataButton() {
        List allBook = getBookDao().loadAll();
        String message = "已有图书数量:" + (allBook == null ? 0 : allBook.size());
        Log.d(TAG, message);
        shortToast(message);
        if (allBook != null) {
            for (Book book : allBook) {
                Log.d(TAG, "图书明细: " + book);
            }
        }
    }

    void shortToast(String message) {
        Toast.makeText(MainActivity.this, message,Toast.LENGTH_SHORT).show();
    }

}


你可能感兴趣的:(基于Sqlcipher和GreenDao的数据库加密)