SQLCipher for Android Application Integration

Community Edition Integration

The community edition of SQLCipher for Android is distributed via the AAR package format. Integration within Gradle can be performed by adding the following entry to the dependencies section of the app/build.gradle file:

compile 'net.zetetic:android-database-sqlcipher:3.5.3@aar'

Commercial Edition Integration

This tutorial will cover integrating the binaries of SQLCipher for Android into an existing Android application. This tutorial assumes the developer has the latest SQLCipher for Android commercial binaries.

We need to copy the various library files over into the root directory of our application. Execute the following commands:

% unzip sqlcipher-for-android-v3.5.3.zip
% mkdir -p app/libs
% cp sqlcipher-for-android-v3.5.3/sqlcipher.jar app/libs
% cp -r sqlcipher-for-android-v3.5.3/armeabi \
        sqlcipher-for-android-v3.5.3/armeabi-v7a \
        sqlcipher-for-android-v3.5.3/x86 app/src/main/jniLibs/

Finally, add the following line to the app/build.gradle file within the dependencies section:

compile fileTree(dir: 'libs', include: ['*.jar'])

Application Usage

Next we will modify the source of the activity to properly initialize the native libraries for SQLCipher and then create our database file inserting a record. In particular, note the import of net.sqlcipher.database.SQLiteDatabase instead of android.database.sqlite.SQLiteDatabase as well as the call to SQLiteDatabase.loadLibs(this). The call to SQLiteDatabase.loadLibs(this) must occur before any other database operation.

package com.demo.sqlcipher;

import java.io.File;
import net.sqlcipher.database.SQLiteDatabase;
import android.app.Activity;
import android.os.Bundle;

public class HelloSQLCipherActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        InitializeSQLCipher();
    }

    private void InitializeSQLCipher() {
        SQLiteDatabase.loadLibs(this);
        File databaseFile = getDatabasePath("demo.db");
        databaseFile.mkdirs();
        databaseFile.delete();
        SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFile, "test123", null);
        database.execSQL("create table t1(a, b)");
        database.execSQL("insert into t1(a, b) values(?, ?)", new Object[]{"one for the money",
                                                                        "two for the show"});
    }
}

The application should now be able to run on either an emulator or device.