SQLCipher for Android Tutorial, encrypt and backup SQLite database[Part3]

In Part1 , we have prepared the Database Handler Class, the User TableDefintion Class where other Tables can be also defined.
The User class ensures reading and writing data from the database.

In Part2  of this tutorial we have use the business logic to create and getting some user information from the database.

In this part, we will try to get and view the SQLite database file from the device and decrypt it using SQLiteManager for windows.

During the development you will be also not able to see the database file and open it with some SQLite Browser software, that is because your application resource folder will not be displayed in the internal device storage until you root your device or deploy the application. But there exist a way how to copy the database from the internal device to the external sdcard and from the sdcard we will be able to copy the database file to the Desktop and open it using SQLiteManager.

Hier is the copy code. We can placed anywhere in the Activity, but after creating the Database. More information  in Part 2.


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import android.os.Environment;
import android.util.Log;
import android.os.Environment;

 try {
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();

    if (sd.canWrite()) {
       	 Log.d("DatabaseHandler", "DatabaseHandler: can write in sd");
        //Replace with YOUR_PACKAGE_NAME and YOUR_DB_NAME
        String currentDBPath = "//data//{YOUR_PACKAGE_NAME}//databases//{YOUR_DB_NAME}.db";
       //Replace with YOUR_FOLDER_PATH and TARGET_DB_NAME in the SD card
        String copieDBPath = "/{YOUR_FOLDER_PATH}/{TARGET_DB_NAME}.db";
        File currentDB = new File(data, currentDBPath);
        File copieDB = new File(sd, copieDBPath);
        if (currentDB.exists()) {
       	  Log.d("DatabaseHandler", "DatabaseHandler: DB exist");
    	  @SuppressWarnings("resource")
	  FileChannel src = new FileInputStream(currentDB).getChannel();
    	  @SuppressWarnings("resource")
	  FileChannel dst = new FileOutputStream(copieDB).getChannel();
    	  dst.transferFrom(src, 0, src.size());
    	  src.close();
    	  dst.close();
    	}
    }
    } catch  (Exception e) {
        e.printStackTrace();
    }

After launching the application on the device, you will find the copied database in the defined copieDBPath.

Please note that  DB Browser for SQLite 3.5.0  software is not supporting SQLCipher decryption for Windows until i write this tutorial.

We will use SQLiteManager that support SQLCipher decryption.

Copie or move the database to your desktop and download the SQLiteManager for windows.

After executing the software open the database file, the SQLiteManager will ask you to give the database password. The Password is defined in the DatabaseHandler class

private static final String DB_PASSWD = "YOUR_SECRET_KEY_HERE";

SQLiteManager_DatabaseKey

You will be able now to see your decrypted database data.
SQLiteManager_Database

Fixes:
if you get one of this errors:
dalvikvm E ERROR: couldn't find native method
dalvikvm E Requested: Lnet/sqlcipher/database/SQLiteDatabase;.native_getDbLookaside

Be sure that you are using the latest SQLCipher for Android
and you have the ZIP file icudt46l.zip in the assets folder.

SQLCipher for Android Tutorial, encrypt and backup SQLite database[Part2]

In Part 1 of this tutorial , we have prepared the Database Handler Class, the TableDefintion Class  where other Tables can be also defined.
The User class ensures reading and writing user data from the database.

In this part we will use the available business logic to create and getting some user information.
I will just give the database code snapshot used in the activity that you have to implemented in your activity, Please read the comment inside.

import de.webandappsolution.Database.DatabaseHandler;
import de.webandappsolution.Database.User;
import de.webandappsolution.Database.TableDefintion.TableUser;

import android.database.Cursor;
import net.sqlcipher.database.SQLiteDatabase;

//Now inside your method , create the DatabaseHandler class instance
SQLiteDatabase.loadLibs(this);
DatabaseHandler db = new DatabaseHandler(this);

// you have to set the ID,NAME,EMAIL and password.
//TIPP: The user password can you hashed before. Maybe using md5 function.
db.addUser(new User(ID,NAME, EMAIL, PASSWORD));

Log.d("DatabaseHandler", "DatabaseHandler: User is created");

we need the addUser() Method. This can be extended in the DatabaseHandler class:

//add this code in the DatabaseHandler class:
//.....
 public void addUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase(DB_PASSWD);

        ContentValues values = new ContentValues();
        values.put(TableUser.USER_ID, user.getID());
        values.put(TableUser.USER_NAME, user.getName());
        values.put(TableUser.USER_EMAIL, user.getEmail());
        values.put(TableUser.USER_PASSWORD, user.getPasswordhash());

        // Inserting Row
        db.insert(TableUser.DB_USER_TABLE, null, values);

        Log.d("DatabaseHandler", "DatabaseHandler: User created");
        db.close(); // Closing database connection

    }

I will prefer to write the different user operation (CRUD) in another class like userOperationHandler.java. so that the DatabaseHandler class can only create and update the database and tables. But this is not a part of this tutorial.

Now the user should be available in the database. If we want to pick up the user data, we can add some code in the same or another activity.We will go throw all the rows in the user database table and we will compare the given email address from the view  with this one saved in the USER_EMAIL column in the database table:

//add this code to your activity:
// you have to pass the email addreess string before. Let say from the view:
EditText emailInput = (EditText) findViewById(R.id.email);
String email = emailInput.getText().toString().trim();

 SQLiteDatabase.loadLibs(this);
 DatabaseHandler db = new DatabaseHandler(this);
 Cursor cursor = db.getUser(db);
 cursor.moveToFirst();
 boolean loginstatus = false;
do
 {
    if( email.equals(cursor.getString(2)) ) {
       loginstatus = true;
    }
  }while(cursor.moveToNext());

  if(loginstatus){
     Log.d("DatabaseHandler", "DatabaseHandler: Email address found");

  }else{
      Log.d("DatabaseHandler", "DatabaseHandler: Email address not found");
  }

Now we have to add the getUser() method inside the DatabaseHandler class.
Note: getString(2) is the second selected value from the query. The index is in the columns String below

     public Cursor getUser(DatabaseHandler databasehandler){
    	SQLiteDatabase db = this.getReadableDatabase(DB_PASSWD);

        //Note:getString(0) == TableUser.USER_ID and getString(2) == TableUser.USER_EMAIL
    	String[] columns =  {TableUser.USER_ID,TableUser.USER_NAME,TableUser.USER_EMAIL};

    	Cursor cursor = db.query(TableUser.DB_USER_TABLE , columns, null, null, null, null, null);

    	return cursor;
    }

In the addUser() and the getUser() method we give always the Database Password to decrypt the requested data . The DB_PASSWD String is defined in the variable definition in the DatabaseHandler class.

In Part3 we will try to get and view the SQLite database from the device and decrypt it using SQLiteManager for windows.
go to Part3 : SQLCipher for Android Tutorial, encrypt and backup SQLite database[Part3]