iwanghang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

如果你的app要使用一个的本地数据库,而数据库的安全又很重要,那么,你就需要加密它,而且是在打包前就加密:

因为apk就是一个压缩包,如果你在app安装的时候,才去加密数据库,对不起,别人已经从apk中解压出来未加密的数据库。

接下来,我们来看看,如何使用sqlcipher给本地数据库加密,并提取出来(我写的只是一种很low的方法,但是真实有效):

0、导包

compile 'net.zetetic:android-database-sqlcipher:3.4.0@aar'

1、首先,我们把要未加密的数据库放在项目中

\SqlEncrypt\app\src\main\res\raw\my_database.db

2、接下来,我们来看下java代码,也就是MainActivity

package com.xxx.sqlencrypt;

import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import net.sqlcipher.database.SQLiteDatabase;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    private String TAG = "MainActivity";
    private String baoName = "com.xxx.sqlencrypt";
    File dbFile = new File("/data"
            + Environment.getDataDirectory().getAbsolutePath()
            + "/" + baoName + "/databases/");
    String dbPath = "/data"
            + Environment.getDataDirectory().getAbsolutePath()
            + "/" + baoName + "/databases/my_database.db";// 要把你Raw文件的db保存到sdcard中

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initPublicDB(); // 初始化数据库

        try {
            encrypt(this,"my_database.db","123456"); // 加密数据库
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 加密函数
     * 来源:https://www.jianshu.com/p/3baf311f8c8c
     */
    public void encrypt(Context ctxt, String dbName,
                        String passphrase) throws IOException {
        File originalFile = ctxt.getDatabasePath(dbName); // 获取数据库路径

        if (originalFile.exists()) { // 判断数据库是否存在
            Log.i("SSS","db yes");
        }else {
            Log.i("SSS","db no");
        }

        if (originalFile.exists()) {
            File newFile =
                    File.createTempFile("sqlcipherutils", "tmp",
                            ctxt.getCacheDir());
            SQLiteDatabase.loadLibs(getApplicationContext());
            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);
        }
    }

    /**
     * 初始化数据库
     */
    private void initPublicDB() {
        if (!dbFile.exists()) { // 如果文件夹不存在,则创建新的文件夹
            dbFile.mkdirs();
        }
        if (!(new File(dbPath).exists())) {  //判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库
            Log.v(TAG, "导入数据库到/" + baoName + "/databases/");
            InputStream is = getResources().openRawResource(R.raw.my_database); // 要导入的数据库
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(dbPath);
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.v(TAG, " " + (new File(dbPath).exists()));
    }
}

3、完事了

4、也可以说,没完事,因为加密的数据库,我们还没拿出来。

5、怎么拿出来呢,请点击这里→《Android-从手机中拷贝文件到电脑-adb pullhttp://www.cnblogs.com/iwanghang/p/8477420.html

6、真的完事了

7、解密的博客,请看下一篇

posted on 2018-02-27 13:46  iwanghang  阅读(3716)  评论(1编辑  收藏  举报