SQLCipher giving "file is not a database" error after db migration complete and app is killed from recent tabs

I am upgrading my android project from library net.zetetic:android-database-sqlcipher:3.5.9@aar to net.zetetic:sqlcipher-android:4.5.6@aar . It runs fine after updating, but while running, if we killed the app from recent tabs, it starts giving this error from every next launch.

I made all the necessary changes as per the documentation, but this case is different and had no solution given. My code is as follows:

The constructor has been modified and inserted hooks to migrate sqlcipher.

private DbHelper(Context context) {
    super(context,
            databaseName,
            password,
            null,
            databaseVersion,
            1,
            null,
            new SQLiteDatabaseHook() {
                @Override
                public void preKey(SQLiteConnection connection) {

                }

                @Override
                public void postKey(SQLiteConnection connection) {
                    connection.executeRaw("PRAGMA cipher_compatibility=3;", null, null);
                    connection.executeRaw("PRAGMA kdf_iter=1000;", null, null);
                    connection.executeRaw("PRAGMA cipher_default_kdf_iter=1000;", null, null);
                    connection.executeRaw("PRAGMA cipher_migrate;", null, null);
                }
            },
            false);
}

As per the documentation, the hooks should only be executed for the first time of migration. SO I have two separated constructors to take care of this condition and the condition is working as expected. Following is another constructor:

private DbHelper(Context context, String secondLaunchCase) {
    super(context, databaseName, password, null, databaseVersion, 1 , null, null, false);
}

I am encrypting the database password and saving it in file. And using the same password to pass in the constructor above. I verified that password is going the same each time. ALso, for the fresh install, everything is working fine. I am not getting how it affects this if the app is killed? Please help with this.

Hi @ashish,

The PRAGMA cipher_migrate command is only able to migrate existing SQLCipher 1, 2, and 3 series databases which use the default configuration setting values. You are setting non-default kdf_iter and cipher_defaut_kdf_iter values so cipher_migrate will not be able to assist.

Hi @developernotes, thanks for the reply. What modifications would u suggest in above code then?

I removed two lines below from my postKey

connection.executeRaw("PRAGMA kdf_iter=1000;", null, null);
connection.executeRaw("PRAGMA cipher_default_kdf_iter=1000;", null, null);

and it worked like a charm! :grinning: Thank you so much @developernotes ! :pray:

Hi @ashish,

Glad to hear everything is working properly for you!

1 Like