Android 文件已加密或不是数据库:,编译时:从sqlite_master中选择count(*);

Android 文件已加密或不是数据库:,编译时:从sqlite_master中选择count(*);,android,sqlite,encryption,sqlcipher-android,Android,Sqlite,Encryption,Sqlcipher Android,我有一个已经生产多年的应用程序。它附带标准Sqlite DB。该应用程序的最新版本集成了SqlCipher 3.5.6库 在新的数据库中有一些额外的表,所以我用onUpgrade方法创建了它们 我在我的应用程序对象中调用了以下方法 SQLiteDatabase.loadLibs(this); 旧apk中的DB_版本是56,我在新apk中将其设置为57,因此应该调用onUpgrade 我从onUpgrade内部调用encrypt方法 @Override public void o

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

在新的数据库中有一些额外的表,所以我用onUpgrade方法创建了它们

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

SQLiteDatabase.loadLibs(this);
旧apk中的DB_版本是56,我在新apk中将其设置为57,因此应该调用onUpgrade

我从onUpgrade内部调用encrypt方法

@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

当我将新的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):

密码短语的encrypt方法中仍然有一个空字符串参数,但它不起任何作用,因为我在下面的实际encrypt方法中已经注释掉了它

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

我现在得到以下错误:

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)

[更新2]

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

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

        loginValidate.getDB().close();

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

另外,我不确定加密方法中的密码短语。您说不使用密码短语,但这是否意味着输入空字符串或根本不传入密码短语。我将给出以下示例。第一个是原始的,另外两个是我尝试过的

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()));
有人能告诉我为什么数据库没有打开吗

因为您试图用密码短语打开它,但这不起作用,因为数据库没有加密。SQLCipher for Android不会神奇地决定再次尝试打开数据库,这次没有密码,然后调用
onUpgrade()


再说,你是怎么到这种地步的?您应该从用户那里收集密码短语,如果您突然开始询问他们从未设置过的密码短语,用户会觉得您很有趣。相反,您需要为“嘿,让我们切换到加密的数据库!”设置一个特定的UX,用户在其中设置密码短语,然后通过
encrypt()

您可能会遇到以下错误:

文件不是数据库:,编译时:从中选择count() sqlite_master;net.sqlcipher.database.SQLiteException:文件不是 数据库:,编译时:从sqlite_master中选择count()

如果数据库文件仅部分复制到databases文件夹


转到设备资源管理器,转到data/data/your app folder/databases,确保该文件夹中有db文件的有效副本。

Hi Mark,密码短语现在已在应用程序对象中硬编码,我知道不应该这样做,但我正试着实现这一点。最后,我将使用用户的登录密码作为密码短语。@turtleboy:无论如何,您不能在
onUpgrade()
中从未加密切换到加密<打开数据库后调用code>onUpgrade()。你需要在一个封闭的数据库上使用你的
encrypt()
。我已经编辑了文章[Update 1]。如果你有时间,你能看一下吗?我要试着关闭数据库first@turtleboy:同意。数据库需要关闭才能使您的
encrypt()
正常工作。如果我读对了,那么
…AS encrypted KEY…
调用的替换版本应该在
.getAbsolutePath()
之后有一个显式的
,“
”,否则
字符串.format()中的第二个
%s
将从堆栈中提取一个随机字符串。@TripeHound谢谢,但我仍然不确定不使用密码短语是什么意思。我已经在更新2下编辑了这篇文章,我也是。仅仅是那一点代码可能不起作用。
Log.e(TAG, "opened DB using originalFile3");
SQLiteDatabase.loadLibs(this);
        Log.e(TAG, "just called SQLiteDatabase.loadLibs(this)");

        loginValidate.getDB().close();

        try {
            encrypt(mContext, "carefreemobiledb.db", "");
        }catch(Exception e){}
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()));