整合SQLCipher工具到LitePal資料庫框架實現資料庫加密
1.去GitHub上下載LitePal原始碼: 傳送門
解壓下載檔案,如下所示:

image.png
2.刪除無用檔案,選擇自己需要的檔案
因為自己的專案是java編寫的,所以不需要kotlin,download中是以前版本的jar檔案,sample則是使用示例,這些都用不到,所以可以直接刪除。如果你還不瞭解LitePal的使用, 傳送門
3.匯入原始碼到工程:
開啟Android studio 選擇File - > new -> import module 選擇下載下來解壓的資料夾,勾選需要的依賴,因為這裡我已經新增完了,忽略。

image.png
修改sdk編譯版本,以及刪除kotlin的相關依賴,直到專案同步完成。
- 3.1 測試匯入是否正確
在主APP中進行新增"core"和"java" Module,然後開始測試,
這裡簡單的展示一下。即LitePal的簡單實用。 - 3.2 在清單檔案中配置 LitePalApplication
<application android:name="org.litepal.LitePalApplication" ... </application>
- 3.3 新增讀寫許可權
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0); findViewById(R.id.jm).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Student student = new Student("onex", "12", "man"); student.save(); Student student1 = new Student("onex1", "12", "man"); student1.save(); Student student2 = new Student("onex2", "12", "man"); student2.save(); Student student3 = new Student("jaima", "12", "man"); student3.save(); Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show(); } });
然後去檔案管理中找到相應的.db檔案,可以看看是否成功!
4、整合SQLCipher到LitePal中
從下載下來的原始碼中可以看出,LitePal的核心程式碼在core這個Module中,所以在該Module中整合SQLCipher,開啟core中的build.gradle,然後新增
api 'net.zetetic:android-database-sqlcipher:4.0.1@aar'
當然可以去官網 https://github.com/sqlcipher/android-database-sqlcipher
使用檢視是否有新的版本,同步後,注意這個地方,sqlcipher使用非常方便,因為它的使用和Android中的SQLiteDatabase的使用是完全一樣,只需要替換掉LitePal原始碼中 android.database.Cursor 和android.database.sqlite.SQLiteDatabase的引用替換成 SQLCipherjar包下的對應類,net.sqlcipher.Cursor 和 net.sqlcipher.database.SQLiteDatabase
-
4.1 需要注意的地方,即設定密碼的地方:
image.png
-
4.2 專案新增依賴
image.png
-
4.3 在APP中進行載入加密的資料庫所需要的so庫檔案!
SQLiteDatabase.loadLibs(this);
5.具體的整合程式碼已分享至 [GitHub]
https://github.com/OnexZgj/SqlcipherMergeLitepal
最後,這裡只是介紹了加密的過程,但是筆者一直有個想法,如何將加密的資料庫檔案解密進行檢視,搜尋了好多的文章,但是還是沒有解決,如果有大佬找到解決方案,希望留言一起探討!