Use SqlCIpher for Android correctly

android-database-sqlcipher is a database encryption framework based on SQLCipher. It supports android4 to android9. It is often used to encrypt Android’s SqlLite. It now supports Gradle integration. If you want to support androidx, you can Using the Room framework, it can also be used with the original SQLiteOpenHelper.

First add dependencies in your build.gradle:

 implementation'net.zetetic:android-database-sqlcipher:4.2.0'  

If you want to be compatible with androidx, please refer to the solution used with the Room framework on the github page.

Here is how to use it with native API:

1. Change all the introduction of android.database.sqlite.* to net.sqlcipher.database.*, such as android. database.sqlite.SQLiteDatabase is changed to net.sqlcipher.database.SQLiteDatabase;

2, call SQLiteDatabase.loadLibs() in the oncreate method of your application; pass in the context of the application as a parameter;

>

3. When you get the database object, use SQLiteDatabase.g(), pass in the password, support String, byte[], char[] as the password;

Here is a guide page As an introduction to use https://www.zetetic.net/sqlcipher/sqlcipher-for-android/

Let’s talk about possible problems during use

  •  SQLiteDatabase mSQLiteDatabase = helper.getWritableDatabase(GlobalConst.DB_PASSWORD);  

    < /li>

Although the guide page is a database object created in onCreate, the actual execution of this code takes a very serious time, usually about 0.8s-1.5s, unlike the original speed It will not freeze soon, so it is recommended to maintain a global single example sentence handle. You can load the database object asynchronously on the application startup loading page and set it as Application global variable or use asynchronous operation every time you need to get the db object. Use the singleton mode to ensure that the db objects that operate the database at the same time are no longer the same thread each time, so asynchronous operations are recommended for all data operations.

  • The password is correct but the data cannot be opened. If you use multiple similar objects inherited from DBHelper, the encryption key is the same and cannot be operated. Either merge these classes, Either separate the database

implementation'net.zetetic:android-database-sqlcipher:4.2.0' 

 SQLiteDatabase mSQLiteDatabase = helper.getWritableDatabase(GlobalConst.DB_PASSWORD);  

< /p>

Leave a Comment

Your email address will not be published.