文件已加密或不是数据库: ,编译时: select count(*) from sqlite_master;

tur*_*boy 5 sqlite encryption android sqlcipher-android

我有一个已经生产多年的应用程序。它附带标准 Sqlite DB。该应用程序的最新版本集成了 SqlCipher 3.5.6 库。

新数据库中有一些额外的表,因此我在 onUpgrade 方法中创建了它们。

我在我的应用程序对象中调用了以下方法。

SQLiteDatabase.loadLibs(this);
Run Code Online (Sandbox Code Playgroud)

旧apk中的DB_VERSION是56,我在新apk中将其设置为57,因此应该调用onUpgrade。

我从 onUpgrade 内部调用加密方法。

@Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            Log.e(TAG, "++++++++++++++++++++++++++SQLiteOpenHelper onUpgrade old version = " + oldVersion + " new version = " + newVersion);

if(oldVersion == 56){

                String sqlToCreateWeeklySummary = String
                        .format("create table %s ( %s INTEGER primary key, %s TEXT, %s TEXT, %s TEXT, %s TEXT, %s TEXT, %s TEXT, %s TEXT)",
                                TABLEWEEKLYSUMMARY, C_ID_WEEKLY_SUMMARY, C_WEEKLY_SUMMARY_STARTDATE,
                                C_WEEKLY_SUMMARY_PLANNEDCALLS, C_WEEKLY_SUMMARY_NCR, C_WEEKLY_SUMMARY_QA, C_WEEKLY_SUMMARY_PLANNEDHOURS,
                                C_WEEKLY_SUMMARY_ACTUALCALLS, C_WEEKLY_SUMMARY_ACTUALHOURS);

                db.execSQL(sqlToCreateWeeklySummary);
                Log.e(TAG, "onUpgrade " + sqlToCreateWeeklySummary);


more table upgrades................

                NfcScannerApplication.setJustUpgradedDBTrue();
                NfcScannerApplication.setDownloadingCompOptsAfterUpgradeTrue();




                try {
                    encrypt(context, "carefreemobiledb.db", "");
                }catch(Exception e){}

            }



        }//end of onUpgrade
Run Code Online (Sandbox Code Playgroud)

public void encrypt(Context ctxt, String dbName, String passphrase) throws IOException {

        Log.e(TAG, "inside encrypt");

        File originalFile=ctxt.getDatabasePath(dbName);

        if (originalFile.exists()) {
            Log.e(TAG, "originalFile exists1");
            File newFile= File.createTempFile("sqlcipherutils", "tmp", ctxt.getCacheDir());
            Log.e(TAG, "created newFile2");

            SQLiteDatabase db= SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
                    "", null, SQLiteDatabase.OPEN_READWRITE);
            Log.e(TAG, "opened DB using originalFile3");

            db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';",
                    newFile.getAbsolutePath(), passphrase));
            Log.e(TAG, "Attached DB4");

            db.rawExecSQL("SELECT sqlcipher_export('encrypted')");

            Log.e(TAG, "export5");

            db.rawExecSQL("DETACH DATABASE encrypted;");
            Log.e(TAG, "detached DB6");

            int version=db.getVersion();

            db.close();
            Log.e(TAG, "closed DB7");

            db= SQLiteDatabase.openDatabase(newFile.getAbsolutePath(),
                    passphrase, null,
                    SQLiteDatabase.OPEN_READWRITE);

            Log.e(TAG, "opened DB with newFile8");

            db.setVersion(version);
            Log.e(TAG, "set version for db using newFile9");
            db.close();
            Log.e(TAG, "closed db10");

            originalFile.delete();
            Log.e(TAG, "deleted orignial file11");
            newFile.renameTo(originalFile);
            Log.e(TAG, "renamed newFile to orginalFile12");
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我将新的 apk 加载到安装了旧应用程序的设备上时,出现以下错误。

file is encrypted or is not a database: , while compiling: select count(*) from sqlite_master;
                                           net.sqlcipher.database.SQLiteException: file is encrypted or is not a database: , while compiling: select count(*) from sqlite_master;
                                               at net.sqlcipher.database.SQLiteCompiledSql.native_compile(Native Method)
                                               at net.sqlcipher.database.SQLiteCompiledSql.compile(Unknown Source)
                                               at net.sqlcipher.database.SQLiteCompiledSql.<init>(Unknown Source)
                                               at net.sqlcipher.database.SQLiteProgram.<init>(Unknown Source)
                                               at net.sqlcipher.database.SQLiteQuery.<init>(Unknown Source)
                                               at net.sqlcipher.database.SQLiteDirectCursorDriver.query(Unknown Source)
                                               at net.sqlcipher.database.SQLiteDatabase.rawQueryWithFactory(Unknown Source)
                                               at net.sqlcipher.database.SQLiteDatabase.rawQuery(Unknown Source)
                                               at net.sqlcipher.database.SQLiteDatabase.keyDatabase(Unknown Source)
                                               at net.sqlcipher.database.SQLiteDatabase.openDatabaseInternal(Unknown Source)
                                               at net.sqlcipher.database.SQLiteDatabase.openDatabase(Unknown Source)
                                               at net.sqlcipher.database.SQLiteDatabase.openOrCreateDatabase(Unknown Source)
                                               at net.sqlcipher.database.SQLiteOpenHelper.getWritableDatabase(Unknown Source)
                                               at net.sqlcipher.database.SQLiteOpenHelper.getReadableDatabase(Unknown Source)
                                               at net.sqlcipher.database.SQLiteOpenHelper.getReadableDatabase(Unknown Source)
                                               at com.carefreegroup.rr3.g.c(Unknown Source)
                                               at com.carefreegroup.rr3.EntryActivity.onCreate(Unknown Source)
                                               at android.app.Activity.performCreate(Activity.java:6912)
                                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
                                               at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                               at android.os.Looper.loop(Looper.java:154)
                                               at android.app.ActivityThread.main(ActivityThread.java:6688)
                                               at java.lang.reflect.Method.invoke(Native Method)
                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
04-26 10:40:53.332 9417-9417/? E/SQLiteOpenHelper: Couldn't open carefreemobiledb.db for writing (will try read-only):
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

SO 上的其他帖子说加密方法上的密码需要是空字符串,以便 SqlCipher 可以打开未加密的数据库。

我已将加密方法的密码设置为“”,但日志显示无法打开数据库。

谁能告诉我为什么数据库没有被打开?它还没有达到 onUpgrade 方法。

注意。值得注意的是,当我清除应用程序上的数据时,它工作正常。

[更新1]

我已将加密方法移至 Application 类中。在 Application 类的 onCreate 中,我调用:

SQLiteDatabase.loadLibs(this);
        Log.e(TAG, "just called SQLiteDatabase.loadLibs(this)");


        try {
            encrypt(mContext, "carefreemobiledb.db", "");
        }catch(Exception e){}
Run Code Online (Sandbox Code Playgroud)

密码的加密方法中仍然有一个空字符串参数,但它没有执行任何操作,因为我在下面的实际加密方法中将其注释掉了。

public static void encrypt(Context ctxt, String dbName, String passphrase) throws IOException {

        File originalFile=ctxt.getDatabasePath(dbName);

        if (originalFile.exists()) {
            Log.e(TAG, "originalFile exists1");
            File newFile= File.createTempFile("sqlcipherutils", "tmp", ctxt.getCacheDir());
            Log.e(TAG, "created newFile2");

            SQLiteDatabase db= SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
                            "", null, SQLiteDatabase.OPEN_READWRITE);
            Log.e(TAG, "opened DB using originalFile3");

//          db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';",
//                  newFile.getAbsolutePath(), passphrase));
            db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';",
                    newFile.getAbsolutePath()));
            Log.e(TAG, "Attached DB4");

            db.rawExecSQL("SELECT sqlcipher_export('encrypted')");

            Log.e(TAG, "export5");

            db.rawExecSQL("DETACH DATABASE encrypted;");
            Log.e(TAG, "detached DB6");

            int version=db.getVersion();

            db.close();
            Log.e(TAG, "closed DB7");

            db= SQLiteDatabase.openDatabase(newFile.getAbsolutePath(),
                            passphrase, null,
                            SQLiteDatabase.OPEN_READWRITE);

            Log.e(TAG, "opened DB with newFile8");

            db.setVersion(version);
            Log.e(TAG, "set version for db using newFile9");
            db.close();
            Log.e(TAG, "closed db10");

            originalFile.delete();
            Log.e(TAG, "deleted orignial file11");
            newFile.renameTo(originalFile);
            Log.e(TAG, "renamed newFile to orginalFile12");
        }
    }
Run Code Online (Sandbox Code Playgroud)

我现在收到以下错误:

04-26 13:56:02.793 15460-15460/? E/NfcScannerApplication: just called SQLiteDatabase.loadLibs(this)
04-26 13:56:02.793 15460-15460/? E/NfcScannerApplication: originalFile exists1
04-26 13:56:02.794 15460-15460/? E/NfcScannerApplication: created newFile2
04-26 13:56:02.798 15460-15460/? E/NfcScannerApplication: opened DB using originalFile3
04-26 13:56:02.806 3247-3247/? E/audit: type=1320 audit(1493211362.789:23690): 
04-26 13:56:02.817 3247-3247/? E/audit: type=1320 audit(1493211362.799:23691): 
04-26 13:56:02.828 3247-3247/? E/audit: type=1320 audit(1493211362.809:23692): 
04-26 13:56:02.886 15460-15469/? E/Database: close() was never explicitly called on database '/data/user/0/com.carefreegroup.rr3/databases/carefreemobiledb.db' 
                                             net.sqlcipher.database.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
                                                 at net.sqlcipher.database.SQLiteDatabase.<init>(Unknown Source)
                                                 at net.sqlcipher.database.SQLiteDatabase.openDatabase(Unknown Source)
                                                 at net.sqlcipher.database.SQLiteDatabase.openDatabase(Unknown Source)
                                                 at net.sqlcipher.database.SQLiteDatabase.openDatabase(Unknown Source)
                                                 at net.sqlcipher.database.SQLiteDatabase.openDatabase(Unknown Source)
                                                 at com.carefreegroup.rr3.NfcScannerApplication.a(Unknown Source)
                                                 at com.carefreegroup.rr3.NfcScannerApplication.onCreate(Unknown Source)
                                                 at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1032)
                                                 at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5881)
                                                 at android.app.ActivityThread.-wrap3(ActivityThread.java)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:154)
                                                 at android.app.ActivityThread.main(ActivityThread.java:6688)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Run Code Online (Sandbox Code Playgroud)

它达到以下目的并崩溃:

Log.e(TAG, "opened DB using originalFile3");
Run Code Online (Sandbox Code Playgroud)

[更新2]

我不确定我是否正确关闭数据库。LoginValidate 是我的数据库类,它公开了一个返回数据库对象的方法。

SQLiteDatabase.loadLibs(this);
        Log.e(TAG, "just called SQLiteDatabase.loadLibs(this)");

        loginValidate.getDB().close();

        try {
            encrypt(mContext, "carefreemobiledb.db", "");
        }catch(Exception e){}
Run Code Online (Sandbox Code Playgroud)

我也不确定加密方法中的密码。您说不使用密码,但这是否意味着空字符串或根本不传递密码。我将举以下例子。第一个是原来的,另外两个是我试过的。

Log.e(TAG, "opened DB using originalFile3");

            db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';",
                    newFile.getAbsolutePath(), passphrase));




Log.e(TAG, "opened DB using originalFile3");

            db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';",
                    newFile.getAbsolutePath(), ""));



Log.e(TAG, "opened DB using originalFile3");

            db.rawExecSQL(String.format("ATTACH DATABASE '%s';",
                    newFile.getAbsolutePath()));
Run Code Online (Sandbox Code Playgroud)

Com*_*are 1

谁能告诉我为什么数据库没有被打开?

因为您尝试使用密码打开它,但这是行不通的,因为数据库未加密。SQLCipher for Android 不会神奇地决定尝试第二次打开数据库(这次没有密码),然后调用onUpgrade().

再说了,你是怎么到这个地步的?您应该从用户那里收集密码,如果您突然开始要求他们从未设置过的密码,用户会奇怪地看着您。相反,您需要有一个特定的用户体验“嘿,让我们切换到加密数据库!”,其中用户设置密码,然后您通过encrypt().