標籤:sqlite3 sqlcipher android
sqlite是一款開源的輕量級資料庫,現在android和ios都在使用它來儲存結構化資料,但是加密版的並非開源。折中一下只能找開源的解決方案,sqlcipher是一個不錯的選擇,它可以對sqlite實現加密,並且有在android和ios都有相應的庫進行解密讀取,只是引入的庫會增加app的大小。SQLCipher is an open source library that provides transparent, secure 256-bit AES encryption of SQLite database files.
1.下載原始碼
官方原始碼:https://github.com/sqlcipher/sqlcipher
2、相關的依賴
安裝openssl及tcl,這兩個依賴必須安裝,不然就會很悲劇
openssl 使用yum openssl-devel 安裝,tcl使用yum tcl-devel安裝
3、編譯
./configure –enable-tempstore=yes CFLAGS=”-DSQLITE_HAS_CODEC” LDFLAGS=”-lcrypto”
make
4.驗證編譯是否成功
建立一個加密的資料,密碼是aaa:
$ sqlcipher test.sqlite
SQLite version 3.7.14.1 2012-10-04 19:37:12
Enter “.help” for instructions
Enter SQL statements terminated with a “;”
sqlite> PRAGMA key = ‘aaa’;
sqlite> create table a(ind int);
sqlite> .tables
a
sqlite> .quit
嘗試不輸入密碼,直接讀取資料庫,理論上是讀不到資料,或者報錯:
$ sqlcipher test.sqlite
SQLite version 3.7.14.1 2012-10-04 19:37:12
Enter “.help” for instructions
Enter SQL statements terminated with a “;”
sqlite> .tables
sqlite> .quit
嘗試正確輸入密碼,應該成功讀取:
$ sqlcipher test.sqlite
SQLite version 3.7.14.1 2012-10-04 19:37:12
Enter “.help” for instructions
Enter SQL statements terminated with a “;”
sqlite> PRAGMA key = ‘aaa’;
sqlite> .tables
a
sqlite> .quit
給現有資料進行加密
如何給現有的sqlite檔案進行加密,沒有別的簡單的方法:
1.先把資料匯出:
$ sqlite3 ifood.sqlite
>.output ifood.sql
>.dump
2.建立一個新的加密的資料庫:
$ sqlcipher ifood_lock.sqlite
sqlite> PRAGMA key = ‘abcdef’; # 設定密碼
3.匯入資料
>.read ifood.sql
SQLCipher For Android
https://github.com/sqlcipher/sqlcipher
這是源碼需要編譯,比較麻煩,可以到http://download.csdn.net/detail/wdxin1322/8378519
使用很簡單,可以參照 https://www.zetetic.net/sqlcipher/sqlcipher-for-android/,然後將項目中的sqllite 的import改成相應的SQLCipher就可以了
我的個人部落格程式猿日記——王德新的個人部落格
sqlite3加密方案sqlcipher,及sqlcipher使用指南