Android新优化

DbFlow sqlcipher 加密存储

2018-06-22  本文已影响0人  DYP_ddbc

前言

在学习Dbflow的使用过程中,发现官方文档没有对其加密的方式进行说明,遂进行了总结
DbFlow可以通过加入sqlcipher来达到数据库加密功能,具体流程如下:

1. 导入相关数据

build.gradle

def dbflow_version = "4.2.4"
def sqlcipher_version = "3.5.9"

annotationProcessor "com.github.Raizlabs.DBFlow:dbflow-processor:${dbflow_version}"
    compile "com.github.Raizlabs.DBFlow:dbflow-core:${dbflow_version}"
    compile "com.github.Raizlabs.DBFlow:dbflow:${dbflow_version}"
    compile "com.github.Raizlabs.DBFlow:dbflow-sqlcipher:${dbflow_version}" //加密必要
    compile "com.github.Raizlabs.DBFlow:dbflow-rx2:${dbflow_version}"
    compile "net.zetetic:android-database-sqlcipher:${sqlcipher_version}@aar" //加密必要
2. 构建数据库
@Database(name = TestDatabase.NAME, version = TestDatabase.VERSION)
public class TestDatabase {
    public static final String NAME = "TestDatabase";

    public static final int VERSION = 1;
}

3. 继承加密工具类,传入加密的key

作为测试,加密的key固定为32个0

public class SQLCipherHelperImpl extends SQLCipherOpenHelper {
    public SQLCipherHelperImpl(DatabaseDefinition databaseDefinition, DatabaseHelperListener listener) {
        super(databaseDefinition, listener);
    }

    /**
     * @return The SQLCipher secret for opening this database.
     */
    @Override
    protected String getCipherSecret() {
        byte[] key = new byte[32];
        Arrays.fill(key, (byte) 0);
        String input = new String(key);
        return input;
    }
}

4. 在自定义Application中初始化 Dbflow

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FlowConfig flowConfig = FlowConfig.builder(this)
                .addDatabaseConfig(new DatabaseConfig.Builder(TestDatabase.class)
                        .openHelper(new DatabaseConfig.OpenHelperCreator() {
                            @Override
                            public OpenHelper createHelper(DatabaseDefinition databaseDefinition, DatabaseHelperListener helperListener) {
                                return new SQLCipherHelperImpl(databaseDefinition, helperListener);
                            }
                        })
                        .build())
                .build();
        FlowManager.init(flowConfig);
    }
}


在上述操作后,App通过Ddflow保存的数据都会加密

PS1: 实际使用中,数据库的加密key不应该使用固定的值,应该在App第一次运行时动态生成并使用

上一篇下一篇

猜你喜欢

热点阅读