Android Database Encryption

Source: Internet
Author: User
Tags sqlite database

A brief introduction to one by one

SQLite is a lightweight, cross-platform, open-source database engine. It has the advantage of reading and writing efficiency, total resource consumption, delay time and overall simplicity, making it the best solution for mobile platform database (such as Android, IOS).

The Android system has a built-in SQLite database. It also provides a complete set of APIs for adding and checking the database. Specifically, it is not specified.

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


Two-way solution

1.SQLite Encryption method
There are two ways to encrypt a database:
Encrypt content before writing to the database
This way is easy to use. In the warehousing/out library only need to do the corresponding encryption and decryption operations can, to a certain extent, to overcome the problem of naked exposure to data.
The only way to do this is not to be completely encrypted. Information such as the table structure of the database can be looked up. 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 in such a way that it can basically solve the information security problem of the database. Today's existing SQLite encryption is basically done in this way.



2.SQLite Encryption Tool

Today we are talking about an open source SQLite encryption tool SQLCipher. Sqlcipher is completely 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 basic encryption interface and SQLite are the same, but also added some of their own interfaces.

In fact, SQLite has encryption and decryption interface, only the free version number is not implemented.

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

For cross-platform support, official notes such as the following:

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 at the same time.


3.Sqlcipher Integration

Sqlcipher official provides specific documentation of the integration, see here.

Here's a simple demo sample demonstrating how to integrate Sqlcipher into our projects at high speed.

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, after decompression for example, as seen below:



Copy all the files under the Libs and assets folders to our current project, after the copy is complete such as the following:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdg9wx2nvzgu=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">


3.3 Operational databases

First, your own definition of Mysqliteopenhelper inherits from the Net.sqlcipher.database.SQLiteOpenHelper class, not android.database.sqlite. Sqliteopenhelper, remember! The demo 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 run the 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);, code such as the following:

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 code (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




Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Android Database Encryption

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.