Android Database security solution, using Sqlcipher for encryption and decryption

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/11952409

As we all know, 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. Database storage is a kind of storage that we often use, I believe most of our friends are familiar with the way it is used. In Android, we can either use native SQL statements to manipulate the data, or use the crud methods provided by the Android API to manipulate the database, each of which has its own characteristics and which one chooses to use as a personal preference.

However, there is a problem with using SQLite to store data. Since most Android phones are rooted, the root of the phone can be accessed into the/data/data/<package_name>/databases directory, where you can view all the data stored in the database. If the general data is OK, but when it comes to some account password, or chat content, our program will face serious security vulnerabilities. So today, let's look at how to use Sqlcipher to solve this security problem.

Sqlcipher is an open source database extended on the basis of SQLite, it is mainly on the basis of SQLite to increase the data encryption function, if we use it in the project to store data, it can greatly improve the security of the program. Sqlcipher supports many different platforms, and the nature of what we're learning here is the use of Sqlcipher in Android.

Let's start by downloading the Sqlcipher toolkit that the Android project relies on:

Https://s3.amazonaws.com/sqlcipher/SQLCipher+for+Android+v2.2.2.zip

Then unzip the toolkit, you will see the assets and Libs in the two directories, and later need to add the contents of these two directories to the Android project. So now we're going to create a new Android project called Sqlciphertest.

Observing the project structure of Sqlciphertest and discovering that there is also a assets directory and a libs directory, it is now possible to copy the contents of these two directories in the Sqlcipher Toolkit. Do not need to copy all the files, select the necessary files to copy it, the completion of the project structure diagram as shown below, the diagram shows the files are necessary.

The preparation is done here, and then we begin to write the code. First create a mydatabasehelper inherit from Sqliteopenhelper, note that this is not the Sqliteopenhelper in the Android API, Instead of the Sqliteopenhelper under the Net.sqlcipher.database package, the code looks like this:

ImportAndroid.content.Context;Importnet.sqlcipher.database.SQLiteDatabase;Importnet.sqlcipher.database.SQLiteDatabase.CursorFactory;ImportNet.sqlcipher.database.SQLiteOpenHelper; Public classMydatabasehelperextendsSqliteopenhelper { Public Static FinalString create_table = "CREATE TABLE book (name text, pages integer)";  PublicMydatabasehelper (context context, String name, Cursorfactory factory,intversion) {        Super(context, name, Factory, version); } @Override Public voidonCreate (Sqlitedatabase db) {db.execsql (create_table); } @Override Public voidOnupgrade (Sqlitedatabase db,intArg1,intarg2) {    }}

In addition to the introduction of the package is not the same, the other usage and the traditional sqliteopenhelper are identical. As you can see, we created a book table in the OnCreate () method, with the two columns of name and pages in the book list.

Next, open or create a new activity_main.xml as the main layout file for your program, as shown in the following code:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" >        <ButtonAndroid:id= "@+id/add_data"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Add Data"        />        <ButtonAndroid:id= "@+id/query_data"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Query data"        /></LinearLayout>

This is simply to place two buttons for adding and querying data, respectively. Next open or new mainactivity as the program main activity, the code is as follows:

 Public classMainactivityextendsActivity {PrivateSqlitedatabase DB; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Sqlitedatabase.loadlibs ( This); Mydatabasehelper DBHelper=NewMydatabasehelper ( This, "Demo.db",NULL, 1); DB= Dbhelper.getwritabledatabase ("Secret_key"); Button AddData=(Button) Findviewbyid (r.id.add_data); Button Querydata=(Button) Findviewbyid (r.id.query_data); Adddata.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {contentvalues values=Newcontentvalues (); Values.put ("Name", "Da Vinci Code"); Values.put ("Pages", 566); Db.insert ("Book",NULL, values);        }        }); Querydata.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {cursor cursor= Db.query ("book",NULL,NULL,NULL,NULL,NULL,NULL); if(Cursor! =NULL) {                     while(Cursor.movetonext ()) {String name= Cursor.getstring (Cursor.getcolumnindex ("name")); intPages = Cursor.getint (Cursor.getcolumnindex ("pages")); LOG.D ("TAG", "book name is" +name); LOG.D ("TAG", "book pages are" +pages);            }} cursor.close ();    }        }); }}

As you can see, in the OnCreate () method, the Sqlitedatabase loadlibs () static method is called first to load the so library that the sqlcipher depends on. Note that this is using the Sqlitedatabase under the Net.sqlcipher.database package. We then created an instance of Mydatabasehelper and called the Getwritabledatabase () method to get the Sqlitedatabase object. Here, when calling the Getwritabledatabase () method, a string parameter is passed in, which is the key that Sqlcipher relies on, and sqlcipher will use the key specified here when adding and decrypting the database.

In the Click event of the Add Data button, we built a piece of data through contentvalues and then called the Sqlitedatabase Insert () method to insert the data into the Book table.

In the Click event of the Query data button, we call Sqlitedatabase's query () method to inquire the data in the Book table, and the results will be stored in the cursor object, note that the cursor under the Net.sqlcipher package is used here. The cursor object is then traversed and the results of the query are printed out.

Now run the program, click the Add Data button, then click the Query Data button, the data just added should be printed in the console.

Do you feel that using the API provided by Sqlcipher and using the native Android database API is almost identical. Yes, Sqlcipher has made an image of all database-related APIs in the Android SDK, allowing developers to manipulate Sqlcipher as if they were a common database file, and all of the data encryption and decryption operations are handled by the sqlcipher behind us.

In this case, we have not experienced the effect of Sqlcipher encryption, now take a look at it, first through the command line to access the Demo.db this database file:

/data/data/com.example.sqlciphertest/-linedemo.db.table

Try to view all the tables in demo.db, and the results return as shown:

As you can see, the execution of the. Table command was rejected because the database file was encrypted.

In addition to using the command line, we can also try to open the database file using Root Explorer, as shown in the following example:

Unsurprisingly, it turned out to be a failure. This is enough to show that the data in the current database is very secure, only the API provided by the Sqlcipher in the application can access the data in the database, in other ways cannot get its data.

The point to be reminded is that after the introduction of Sqlcipher in the project, you will be able to increase the volume of your program, the APK will probably be larger than a few m, is more focused on file size, or more focused on program security, you should be based on specific needs to make the appropriate judgment.

Well, today's explanation to this end, a friend in doubt please leave a message below.

SOURCE download, please click here

Android Database security solution, using Sqlcipher for encryption and decryption

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.