1

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?

2 Answers2

0

Like you are using the cipher for the first time in a previously non-ciphered database, then I recommend you to force that the database to be re-created.

To do that, you can simply change your database name in your DatabaseHelper class. Once you change the database name, when your device updates the onCreate() will trigger and it will create all your database from zero.

public class YourDatabaseHelper extends SQLiteOpenHelper {

   public final static String DATABASE_NAME = Constants.DATABASE_NAME; // Change the name to force the database to be created from zero.
   public final static int CURRENT_VERSION = Constants.DATABASE_VERSION_INT;


   public DatabaseHelper(Context context){
       super(context, DATABASE_NAME, null, CURRENT_VERSION);        
   }

   public void onCreate(SQLiteDatabase db){
       // Create all your tables.
   }

   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
       // No need to do anything in here, because onCreate will be triggered.
   }

}
0

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!