I have been following the official documentation in order to start using SQLCipher Community Edition in the apps I´m developing. So, I made a proper gradle import as following:
compile 'net.zetetic:android-database-sqlcipher:3.5.9@aar'
I added the
@Override
public void onCreate() {
super.onCreate();
SQLiteDatabase.loadLibs(this);
}
in the MainApplication.java.
As my apps are already released, I have placed as well some migration code in onUpgrade() method in my instance of SQLiteOpenHelper class.
Unfortunately, although I upgraded the DB version number, I do the call:
getInstance().getReadableDatabase("testKey");
neither onUpgrade(), nor onCreate() methods won´t be called.
Did I miss something in the configuration?
Finally I found the solution for the problem. Instead of calling the migration functionality inside the onUpgrade() method, I added the migration code before the database is queried for the first time (after opening the app):
public static void encrypt(Context ctxt, File originalFile, char[]
passphrase)
throws IOException {
SQLiteDatabase.loadLibs(ctxt);
if (originalFile.exists()) {
File newFile=
File.createTempFile("sqlcipherutils", "tmp", ctxt.getCacheDir());
SQLiteDatabase db=
SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(), "", null, SQLiteDatabase.OPEN_READWRITE);
db.rawExecSQL("ATTACH DATABASE '" + newFile.getAbsolutePath()+ "' AS encrypted KEY '"+String.valueOf(passphrase)+"'");
db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
db.rawExecSQL("DETACH DATABASE encrypted");
int version=db.getVersion();
db.close();
db=SQLiteDatabase.openDatabase(newFile.getAbsolutePath(), passphrase, null, SQLiteDatabase.OPEN_READWRITE);
db.setVersion(version);
db.close();
originalFile.delete();
newFile.renameTo(originalFile);
}
}
I took the solution from this source. Thanks for the author, whoever he is!