Thursday, January 12, 2017

Use SQLCipher in android to encrypt your SQLite database


package com.example.database;
import android.content.Context;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;

public class SQLCipherOpenHelper extends SQLiteOpenHelper {

    private final static String SQL_KEY = "akshay123";//password
    public static String DATABASE_NAME = "myDB.sqlite";
    public static int DATABASE_VERSION = 5;
    private static SQLCipherOpenHelper mInstance;
    public Context mContext;

    public synchronized static SQLCipherOpenHelper getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SQLCipherOpenHelper(context);
        }
        return mInstance;
    }
    public SQLCipherOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        SQLiteDatabase.loadLibs(context);
    }

//    public SQLCipherOpenHelper(Context context) {
//        super(context, context.getExternalFilesDir(null).getAbsolutePath() + "/" +
// DATABASE_NAME, null, DATABASE_VERSION);
// SQLiteDatabase.loadLibs(context);
//
//    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(MyController.CREATE_TABLE); 
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        onCreate(db);
        db.execSQL(MyController.ADD_REPORT_TITLE);
    }

    public synchronized SQLiteDatabase getWritableDatabase() {

        return super.getWritableDatabase(SQL_KEY);
    }

    public synchronized SQLiteDatabase getReadableDatabase() {

        return super.getReadableDatabase(SQL_KEY);
    }

    public static void removeInstance() {
        mInstance = null;
    }

}



No comments:

Post a Comment