sqlcipher 加密数据库的异常

本文针对移动应用开发中使用SQLCipher加密数据库时遇到的fileisnotadatabase异常,详细解析了问题原因及解决方案,包括如何正确配置SQLiteDatabaseHook以确保数据库正常加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

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

引入版本

  implementation 'net.zetetic:android-database-sqlcipher:4.2.0@aar'

发现问题

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");
            }
        }

结束语

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值