SQLCipher Android,为未加密的数据库设置密钥

时间:2017-01-16 13:44:27

标签: android encryption android-sqlite

我尝试在未加密的现有数据库上运行SQLCipher

我使用的方法似乎有效,但不像SQLCipher那样加密。

public static synchronized SQLiteDatabase openDatabase() {
        try {
            return sDatabaseHelper.getWritableDatabase(KEY);
        } catch (Exception e) {
            android.database.sqlite.SQLiteDatabase sqLiteDatabase = android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(
                    sContext.getDatabasePath(mConfiguration.getDatabaseName()), null);
            sqLiteDatabase.execSQL(String.format("PRAGMA key = '%s'", KEY));
            return sDatabaseHelper.getWritableDatabase(KEY);
        }
    }

P.S它正在自定义ActiveAndroid

上运行

有没有解决方案?

1 个答案:

答案 0 :(得分:0)

找到解决方案,并将其用于ActiveAndroid

public static synchronized SQLiteDatabase openDatabase() {
        try {
            return sDatabaseHelper.getWritableDatabase(KEY);
        } catch (Exception e) {
            try {
                encrypt(getContext(), sDatabaseHelper.getConfiguration().getDatabaseName(), KEY);
                return sDatabaseHelper.getWritableDatabase(KEY);
            } catch (IOException e1) {
                e1.printStackTrace();
                return null;
            }
        }
    }

    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);
        }
    }