我們都知道德撬,Android的數(shù)據(jù)庫文件存儲在/data/data/your_packagename/databases路徑下面痕貌,只要獲得root權(quán)限就可以進入該目錄恳邀,并可以查看沿量、編輯你的應(yīng)用數(shù)據(jù)饼丘,如果你的數(shù)據(jù)庫存儲了一些不允許用戶查看和操作的敏感信息,則必須要給數(shù)據(jù)庫加密仑最。
SQLCipher是基于SQLite的開源數(shù)據(jù)庫扔役,在SQLite的基礎(chǔ)上增加了加密功能,集成已經(jīng)極其很方便警医。
step1
Sqlcipher的官方Android集成文檔已經(jīng)很老舊亿胸,官方團隊在其blog中提到可以arr包的方式集成,即如果你是使用Android studio開發(fā)预皇,那么你只需要在gradle中加入這一句:
compile 'net.zetetic:android-database-sqlcipher:3.4.0@aar'
如果你仍然在使用eclipse開發(fā)侈玄,也很簡單:
- 請?zhí)蕴愕腅clipse,投入Android Studio的懷抱吟温。
step2
創(chuàng)建一個SQLiteOpenHelper序仙,只不過我們應(yīng)該繼承的是net.sqlcipher.database.SQLiteDatabase,而不是Android原本的android.database.sqlite.SQLiteDatabase,然后記得在你的應(yīng)用做任何數(shù)據(jù)庫操作之前調(diào)用SQLiteDatabase.loadLibs(this)去加載SQLCipher所需要的SO庫鲁豪,這一步在郭霖老師的文章中有詳細的例子潘悼,這里不再贅述。
step3
如果你是在新建一個App爬橡,那么看到step2就足夠了治唤,但是如果你像我一樣,早期并未意識到要解密數(shù)據(jù)庫糙申,那就要一起來看看如何將一個已存在的未加密數(shù)據(jù)庫加密肝劲,這個在很多相關(guān)博客中都未提到。
SQLCipher官方提供了一個sqlcipher_export()方法去將未加密的數(shù)據(jù)庫轉(zhuǎn)換成加密數(shù)據(jù)庫郭宝,將加密數(shù)據(jù)庫轉(zhuǎn)換成未加密數(shù)據(jù)庫,官方文檔有詳細說明掷漱。
如果你只關(guān)心在Android中如何實現(xiàn)粘室,那么請看代碼:
public static void encrypt(Context ctxt, String dbName,
String passphrase) throws IOException {
File originalFile = ctxt.getDatabasePath(dbName);
if (originalFile.exists()) {
File newFile =
File.createTempFile("sqlcipherutils", "tmp",
ctxt.getCacheDir());
SQLiteDatabase db =
SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
"", null,
SQLiteDatabase.OPEN_READWRITE);
db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';",
newFile.getAbsolutePath(), passphrase));
db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
db.rawExecSQL("DETACH DATABASE encrypted;");
int version = db.getVersion();
db.close();
db =
SQLiteDatabase.openDatabase(newFile.getAbsolutePath(),
passphrase, null,
SQLiteDatabase.OPEN_READWRITE);
db.setVersion(version);
db.close();
originalFile.delete();
newFile.renameTo(originalFile);
}
}
已加密的數(shù)據(jù)庫轉(zhuǎn)換成未加密數(shù)據(jù)庫類似,大家可以根據(jù)官方文檔自己實現(xiàn)卜范。