Android Database Encryption

Source: Internet
Author: User

A brief introduction

SQLite is a lightweight, cross-platform, open-source database engine that has the advantage of read-write efficiency, total resource consumption, latency, and overall simplicity, making it the best solution for mobile platform databases (such as Android, IOS). The Android system has a built-in SQLite database, and provides a full set of APIs for the database to be used for pruning and checking operations, not specified in detail.

However, the Android platform comes with SQLite with a fatal flaw: encryption is not supported. This results in the data stored in SQLite can be seen by anyone using any text editor. If the normal data is OK, but when it comes to some account password, or chat content, our application will face serious security vulnerabilities.


Second Solution

1.SQLite Encryption method
There are two ways to encrypt a database:
Encrypt content before writing to the database
This method is simple to use, in the storage/out of the library only need to do the corresponding encryption and decryption operations, to a certain extent, to solve the problem of naked exposure to data.
However, this method is not completely encrypted, because the database table structure and other information can be looked at. The search is also a problem when the content that is written to the database is encrypted.
Encrypt the database file
The whole database is encrypted, which basically can solve the information security problem of the database. The existing SQLite encryption is basically implemented in this way.


2.SQLite Encryption Tool

Today we are talking about an open source SQLite encryption tool SQLCipher. Sqlcipher is fully open source and its code is hosted on GitHub.

Sqlcipher uses 256-bit AES encryption, because it is based on the free version of SQLite, the main encryption interface and SQLite are the same, but also add some of their own interfaces. In fact, SQLite has encryption and decryption interface, but the free version is not implemented.

SQLCipher is divided into community Edition and commercial Edition, the former is free, about SQLCipher Features can be see here.

For cross-platform support, the official notes are as follows:

SQLCipher has broad platform-C, Obj-c, QT, Win32/.net, Java, Python, Ruby, Linux, Mac OS X, Iphone/io S, Android, Xamarin.ios, and xamarin.android (such as IOS, Android).

Both Android and IOS platforms are supported.


3.Sqlcipher Integration

Sqlcipher official provides a detailed documentation of the integration, see here.

Here's a simple example of how to quickly integrate Sqlcipher into our project.

3.1 Download the official binaries package

: Https://s3.amazonaws.com/sqlcipher/3.2.0/sqlcipher-for-android-community-v3.2.0.zip

3.2 Importing dependent files

Unzip the downloaded compressed package and unzip it as follows:



Copy all the files in the Libs and assets directories to our current project, after the copy is complete as follows:



3.3 Operational databases

First, the custom Mysqliteopenhelper inherits from the Net.sqlcipher.database.SQLiteOpenHelper class, not the android.database.sqlite. Sqliteopenhelper, remember! The sample code is as follows:

Package Com.ricky.android.sqlitecipher.db;import Com.ricky.android.sqlitecipher.util.logger;import Android.content.context;import Net.sqlcipher.database.sqlitedatabase;import Net.sqlcipher.database.sqlitedatabase.cursorfactory;import Net.sqlcipher.database.sqliteopenhelper;public Class Mysqliteopenhelper extends Sqliteopenhelper {private static final String db_name = "test.db";p rivate static final int Db_v Ersion = 3;public Mysqliteopenhelper (context context) {Super (context, db_name, NULL, db_version);} Public Mysqliteopenhelper (context context, String name,cursorfactory factory, int version) {Super (context, name, factory , version);} @Overridepublic void OnCreate (Sqlitedatabase db) {LOGGER.E ("Mysqliteopenhelper", "OnCreate db name=" +db_name+ "version = "+db_version");d b.execsql ("CREATE TABLE student (id integer PRIMARY KEY autoincrement, Name text, age INTEGER)");} @Overridepublic void Onupgrade (sqlitedatabase db, int arg1, int arg2) {//TODO auto-generated method stub}}


then use the sqlitedatabase to manipulate the database in our DAO class. Note that This is net.sqlcipher.database.SQLiteDatabase, not android.database.sqlite.SQLiteDatabase, do not lead the wrong bag!

Package Com.ricky.android.sqlitecipher.dao;import Java.util.arraylist;import Java.util.list;import Net.sqlcipher.cursor;import Net.sqlcipher.database.sqlitedatabase;import Net.sqlcipher.database.SQLiteOpenHelper ; Import Android.content.contentvalues;import Android.content.context;import Com.ricky.android.sqlitecipher.db.sqlitehelperfactory;import com.ricky.android.sqlitecipher.model.Student;    public class Studentdaoimpl implements Studentdao {private Sqliteopenhelper sqliteopenhelper;    Private String Password = "Ricky"; Public Studentdaoimpl (Context context) {Sqliteopenhelper = Sqlitehelperfactory.create (context);} @Overridepublic Long Insert (Student stu) {Sqlitedatabase db = Null;try{db = Sqliteopenhelper.getwritabledatabase ( password);              Contentvalues values = new Contentvalues ();              Values.put ("name", "Ricky");              Values.put ("Age", 24); Return Db.insert ("student", null, values);} Finally{if (Db!=null) Db.close ();}} @Overridepublic list<student> queRy () {sqlitedatabase db = null;            cursor cursor = NULL;TRY{DB = sqliteopenhelper.getwritabledatabase (password); cursor = db.query ("Student", New string[]{"id", "name", "age"}, NULL, NULL, NULL, NULL, NULL); list<student> list = new arraylist<> (); while (Cursor!=null && cursor.movetonext ()) {Student Stu = new Student (); Stu.setid (Cursor.getint (0)); Stu.setname (cursor.getstring (1)); Stu.setage (Cursor.getint (2)); List.add ( Stu);} return list;} Finally{if (cursor!=null) {cursor.close ();} if (db!=null) Db.close ();}}}

The crud to the data here is basically implemented, but one more thing to be aware of: you must first call Sqlitedatabase.loadlibs (context), and then perform database-related operations.

For ease of management, I wrote a separate sqlitehelperfactory class to be responsible for the creation of the Sqliteopenhelper, which will be called Sqlitedatabase.loadlibs after the Mysqliteopenhelper object is created ( context), the code is as follows:

Package Com.ricky.android.sqlitecipher.db;import Com.ricky.android.sqlitecipher.util.logger;import Android.content.context;import Net.sqlcipher.database.sqlitedatabase;import net.sqlcipher.database.sqliteopenhelper;/** * Sqliteopenhelper Factory * @author Ricky * */public class Sqlitehelperfactory {p Rivate static final String TAG = SQLiteHelperFactory.class.getSimpleName ();p rivate static Sqliteopenhelper Sqliteopenhelper;private sqlitehelperfactory () {}public static Sqliteopenhelper Create (context context) {if ( Sqliteopenhelper==null) {synchronized (Sqlitehelperfactory.class) {if (sqliteopenhelper==null) {LOGGER.E (TAG, "Init Sqliteopenhelper "); sqliteopenhelper = new Mysqliteopenhelper (Context.getapplicationcontext ()); LOGGER.E (TAG, "Sqlitedatabase loadlibs");//Must call this method first sqlitedatabase.loadlibs (context);}}} return sqliteopenhelper;}}


And finally the Mainactivity class.

Package Com.ricky.android.sqlitecipher;import Java.util.list;import Com.ricky.android.sqlitecipher.dao.StudentDAO ; Import Com.ricky.android.sqlitecipher.dao.studentdaoimpl;import com.ricky.android.sqlitecipher.model.Student; Import Com.ricky.android.sqlitecipher.util.logger;import Android.app.activity;import Android.os.Bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class MainActivity Extends Activity implements Onclicklistener {private static final String TAG = MainActivity.class.getSimpleName (); Private button Bt_insert;private button bt_query;private Studentdao studentdao; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); FindViewById (); Setlistener ();p rocesslogic ();} private void Findviewbyid () {Bt_insert = (button) Findviewbyid (r.id.bt_insert); bt_query = (Button) Findviewbyid (r.id.bt _query);} private void Setlistener () {bt_insert.setonclicklistEner (this); Bt_query.setonclicklistener (this);} private void Processlogic () {Studentdao = new Studentdaoimpl (this);} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case R.id.bt_insert:student stu = new Student (); Stu.setname ("Mi Ke "); stu.setage (); Long id = Studentdao.insert (stu); LOGGER.I (TAG, "Insert id=" +id); break;case r.id.bt_query:list<student> List = Studentdao.query (); if (list!=null) {logger.i (TAG, "Student list size=" +list.size ());} ELSE{LOGGER.I (TAG, "Student list is empty"); Break;default:break;}}}



OK, about the integration of sqlcipher here is done, and finally attached to the demo source (see article at the end), if there is a problem can be a message to exchange it!





demo:http://download.csdn.net/detail/fx_sky/8165223




Android Database Encryption

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.