首页 > 解决方案 > Android自定义迁移Sqlcipher从3到4

问题描述

我在我的应用程序中将 Sqlcipher for Android 从 3.5.7 升级到了 4.1.3。

对于使用 Sqlcipher 3 创建的现有数据库,我需要自定义迁移,因为它基于自定义参数,本文的选项 3 也说明了这一点。

当我尝试打开数据库时出现此异常。

net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master;
    at net.sqlcipher.database.SQLiteCompiledSql.native_compile(Native Method)

这是我的代码:

        SQLiteDatabaseHook mHook = new SQLiteDatabaseHook() {
            public void preKey(SQLiteDatabase database) {
                database.rawExecSQL("PRAGMA kdf_iter=1000;");
                database.rawExecSQL("PRAGMA cipher_default_kdf_iter=1000;");
                database.rawExecSQL("PRAGMA cipher_page_size = 4096;");
            }

            public void postKey(SQLiteDatabase database) {
                database.rawExecSQL("PRAGMA cipher_compatibility=3;");
            }
        };

        // this line generate the exception
        SQLiteDatabase database = SQLiteDatabase.openDatabase(oldDatabaseFile.getAbsolutePath(), password, null, SQLiteDatabase.OPEN_READWRITE, mHook);
        ...
        // migration code with ATTACH, sqlcipher_export etc... 
        ...

该文件存在并且密码正确:如果我降级 Sqlcipher 库,则相同的代码可以工作。我做错了什么?

标签: androiddatabase-migrationsqlciphersqlcipher-android

解决方案


我发现了错误:

我使用 sqlchipher 3 使用参数创建了数据库cipher_page_size = 4096,但它不被接受,因为使用了默认值。

现在尝试迁移,指定我认为使用的参数,它不起作用。我只需要删除此参数并将所有内容放入postKey方法中

private final SQLiteDatabaseHook mHook = new SQLiteDatabaseHook() {
    public void preKey(SQLiteDatabase database) {
    }

    public void postKey(SQLiteDatabase database) {
        database.rawExecSQL("PRAGMA cipher_compatibility=3;");
        database.rawExecSQL("PRAGMA kdf_iter=1000;");
        database.rawExecSQL("PRAGMA cipher_default_kdf_iter=1000;");
    }
};

推荐阅读