sqlcipher 加密数据库的异常

前言

通常我们在做移动应用开发的时候,数据存储是我们一直关注的问题,最常用的当属于数据库,由于考虑到安全性,我们通常采用加密过的数据库,sqlciper便是我们最常见的选择.本文主要描述使用过程中遇到的问题集合.

引入版本

  implementation 'net.zetetic:android-database-sqlcipher:[email protected]'

发现问题

java.lang.RuntimeException: Unable to get provider com.closeli.industry.business.database.CacheDataProvider: 
net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master;
....
Caused by: net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master;
....
  • 通过异常信息,我们看到的为之前的数据库文件不被识别,导致加载出现了异常,又因为该库为第三方工具,我们便需要去查看部分源码,或者去对应的仓库地址查看该问题.

解决方法

  • 查看 加密数据的源码,发现有一个这样的重载方法.
/**
     * Create a helper object to create, open, and/or manage a database.
     * The database is not actually created or opened until one of
     * {@link #getWritableDatabase} or {@link #getReadableDatabase} is called.
     *
     * @param context to use to open or create the database
     * @param name of the database file, or null for an in-memory database
     * @param factory to use for creating cursor objects, or null for the default
     * @param version number of the database (starting at 1); if the database is older,
     *     {@link #onUpgrade} will be used to upgrade the database
     * @param hook to run on pre/post key events
     */
    public SQLiteOpenHelper(Context context, String name, CursorFactory factory,
                            int version, SQLiteDatabaseHook hook) {
        this(context, name, factory, version, hook, new DefaultDatabaseErrorHandler());
    }
  • 具体方式
new SQLiteDatabaseHook() {
            @Override
            public void preKey(SQLiteDatabase database) {

            }

            @Override
            public void postKey(SQLiteDatabase sqLiteDatabase) {
                sqLiteDatabase.execSQL("PRAGMA cipher_page_size = 1024");
                sqLiteDatabase.execSQL("PRAGMA kdf_iter = 64000");
                sqLiteDatabase.execSQL("PRAGMA cipher_hmac_algorithm = HMAC_SHA1");
                sqLiteDatabase.execSQL("PRAGMA cipher_kdf_algorithm = PBKDF2_HMAC_SHA1");
            }
        }

结束语

当我们在使用第三方工具时,遇到问题我们应当首先去对应的仓库中去查看该问题是否存在,其次去查看源码,定位问题的所在.

点赞