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();

Thanks.

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

Hi
Can you please share your final code on how you encrypted your DB please?
Thank You!

Hi @samir

Are you looking to encrypt an existing plaintext SQLite database, or are you creating a new SQLCipher database from scratch? If the former, please take a look at the sqlcipher_export convenience function; for the latter we have documentation for using SQLCipher for Android here.