標籤:android style blog http color 使用 io 資料
Android使用的是開源的SQLite資料庫,資料庫本身沒有加密,加密思路通常有兩個:
1. 對幾個關鍵的欄位使用密碼編譯演算法,再存入資料庫
2. 對整個資料庫進行加密
SQLite資料庫加密工具:收費工具:
- SSE(SQLite Encryption Extension)
免費工具:
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/openssl2 openssl-1.0.1h Admin$ make3 openssl-1.0.1h Admin$ make test4 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.db2 SQLCipher version 3.8.4.3 2014-04-03 16:53:123 Enter ".help" for instructions4 Enter SQL statements terminated with a ";"5 sqlite> PRAGMA key = ‘thisiskey‘;6 sqlite> create table encrypted (id integer, name text);7 sqlite> .schema8 CREATE TABLE encrypted (id integer, name text);9 sqlite> .q
2. 開啟加密資料庫
1 $ sqlcipher encrypted.db2 SQLCipher version 3.8.4.3 2014-04-03 16:53:123 Enter ".help" for instructions4 Enter SQL statements terminated with a ";"5 sqlite> PRAGMA key = ‘thisiskey‘;6 sqlite> .schema7 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:123 Enter ".help" for instructions4 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:123 Enter ".help" for instructions4 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;