Converting sqlite to encrypted database:

后端 未结 2 2027
执笔经年
执笔经年 2021-02-11 02:16

I\'ve an existing sqlite database in my application. It running successfully. Now i need to encrypt the database using sqlcipher. My problem is at the time of converting sqlite

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-11 02:53

    Thanks, it works great. I added this code to encrypt, decrypt and change the password.

    @Override
    public synchronized SQLiteDatabase getWritableDatabase(String password) {
        SQLiteDatabase sqLiteDatabase;
        try{
            sqLiteDatabase = super.getWritableDatabase(password);
        }catch(Exception e){
            try {
                encrypt(context,DATABASE_NAME,PWOLD,PWNEW);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            sqLiteDatabase = super.getWritableDatabase(password);
        }
        return sqLiteDatabase;
    }
    
    @Override
    public synchronized SQLiteDatabase getReadableDatabase(String password) {
        SQLiteDatabase sqLiteDatabase;
        try{
            sqLiteDatabase = super.getReadableDatabase(password);
        }catch(Exception e){
            try {
                encrypt(context, DATABASE_NAME, PWOLD, PWNEW);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            sqLiteDatabase = super.getReadableDatabase(password);
        }
        return sqLiteDatabase;
    }
    
    public static void encrypt(Context context, String dbName,
                               String oldPass, String newPass) throws IOException {
        if(!newPass.isEmpty()) Log.d(TAG,"Encrypt DB...");
        else Log.d(TAG,"Decrypt DB...");
    
        File originalFile=context.getDatabasePath(dbName);
    
        if (originalFile.exists()) {
            File newFile = File.createTempFile("sqlcipherutils", "tmp",
                            context.getCacheDir());
            SQLiteDatabase db = SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
                    oldPass, null,
                    SQLiteDatabase.OPEN_READWRITE);
    
            db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';",
                    newFile.getAbsolutePath(), newPass));
            db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
            db.rawExecSQL("DETACH DATABASE encrypted;");
    
            int version=db.getVersion();
    
            db.close();
    
            db = SQLiteDatabase.openDatabase(newFile.getAbsolutePath(),
                    newPass, null,
                    SQLiteDatabase.OPEN_READWRITE);
            db.setVersion(version);
            db.close();
    
            originalFile.delete();
            newFile.renameTo(originalFile);
        }
    }
    

提交回复
热议问题