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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM