How to apply SQLCipher to pre-existing Room database?

Hi. I’m having issues applying SQLCipher to a previously existing Room database.

SQLCipher works fine to new users who builds the database for the first time,
but for previous users whom already have a built a database, I’m getting the following runtime error.

Android Runtime: FATAL EXCEPTION: arch_disk_io_1
Caused by: net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master

Before applying SQLCipher, room database is created by using the following code:

AppDatabase appDatabase = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, “my-database”).build();

And this is how I applied SQLCipher:

char testBytes = {‘t’, ‘e’, ‘s’, ‘t’};
final byte passphrase = SQLiteDatabase.getBytes(testBytes);
final SupportFactory factory = new SupportFactory(passphrase);

AppDatabase appDatabase = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, “my-database”).openHelperFactory(factory).build();


SQLCipher does not distinguish between “unencrypted database” and “encrypted database with the wrong passphrase”. Ideally, you would track whether or not the database is encrypted. And, at the time you decide that you want to encrypt an unencrypted database, you will need code to encrypt it. This Java method will encrypt an existing unencrypted database.

The getDatabaseState() method on that utility class will attempt to determine if a database is encrypted or not, by trying to open the database with an empty passphrase.

Wow thanks commonsguy!
I’ve got my DB encrypted, thanks to your response!!

1 Like