Android Sqlite数据库加密

Android使用的是开源的SQLite数据库,数据库本身没有加密,加密思路通常有两个:

1. 对几个关键的字段使用加密算法,再存入数据库

2. 对整个数据库进行加密

SQLite数据库加密工具:

收费工具:

免费工具:

SQLCipher使用:

SQLCipher是完全开源的软件,提供256-bit AES加密

源码编译:

1. OpenSSL编译

SQLCipher源码编译需要依赖OpenSSL提供的libcrypto

下载OpenSSL源码,这里选择稳定版本1.0.1h

1 openssl-1.0.1h Admin$ ./config --prefix=/usr/local --openssldir=/usr/local/openssl
2 openssl-1.0.1h Admin$ make
3 openssl-1.0.1h Admin$ make test
4 openssl-1.0.1h Admin$ make install

2. SQLCipher源码编译

下载地址:https://github.com/sqlcipher/sqlcipher

1 sqlcipher Admin$ ./configure --enable-tempstore=yes CFLAGS="-DSQLITE_HAS_CODEC" LDFLAGS="/usr/local/lib/libcrypto.a"
2 sqlcipher Admin$ make

命令行使用:

1. 创建加密数据库

1 $ sqlcipher encrypted.db
2 SQLCipher version 3.8.4.3 2014-04-03 16:53:12
3 Enter ".help" for instructions
4 Enter SQL statements terminated with a ";"
5 sqlite> PRAGMA key = 'thisiskey';
6 sqlite> create table encrypted (id integer, name text);
7 sqlite> .schema
8 CREATE TABLE encrypted (id integer, name text);
9 sqlite> .q

2. 打开加密数据库

1 $ sqlcipher encrypted.db
2 SQLCipher version 3.8.4.3 2014-04-03 16:53:12
3 Enter ".help" for instructions
4 Enter SQL statements terminated with a ";"
5 sqlite> PRAGMA key = 'thisiskey';
6 sqlite> .schema
7 CREATE TABLE encrypted (id integer, name text);

3. 修改数据库密码

1 sqlite> PRAGMA rekey = 'newkey';

4. 加密已有的数据库

1 $ sqlcipher banklist.sqlite3 
2 SQLCipher version 3.8.4.3 2014-04-03 16:53:12
3 Enter ".help" for instructions
4 Enter SQL statements terminated with a ";"
5 sqlite> ATTACH DATABASE 'encrypted.db' AS encrypted KEY 'thisiskey';
6 sqlite> SELECT sqlcipher_export('encrypted');
7 sqlite> DETACH DATABASE encrypted;

5. 解密数据库

1 $ sqlcipher encrypted.db 
2 SQLCipher version 3.8.4.3 2014-04-03 16:53:12
3 Enter ".help" for instructions
4 Enter SQL statements terminated with a ";"
5 sqlite> PRAGMA key = 'thisiskey';
6 sqlite> ATTACH DATABASE 'plaintext.db' AS plaintext KEY '';
7 sqlite> SELECT sqlcipher_export('plaintext');
8 sqlite> DETACH DATABASE plaintext;

Android版本SQLCipher使用

android版本源码,编译需要依赖的东西很多,懒得去试了,可以直接下载已经编译好的binary,官网下载,或者这里为3.1.0版本

注:github上的binary为2.1.1,实际测试在Android 4.4 kitkat上无法使用,请从官网下载最新的3.1.0版本

1. 将解压后的libs和asserts添加到工程:

2. 将工程中原有的android.database.sqlite.*全部替换为net.sqlcipher.database.*,原先的android.database.Cursor可以保留

3. 在activity或者其他调用数据库的地方,注意要在使用数据库之前加上:

1 SQLiteDatabase.loadLibs(this);

备注:使用SQLCipher命令行将原先的数据库加密之后,新数据库的version有可能为0,导致在SQLiteOpenHelper中会进入到onCreate()中,重建数据库。

解决方法,将数据库版本改回原先的版本:

1 sqlite> PRAGMA user_version = 12;

 

posted on 2014-07-29 15:29  treecat  阅读(11877)  评论(1编辑  收藏  举报