Converting sqlite to encrypted database:

后端 未结 2 2028
执笔经年
执笔经年 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:55

    You are using databaseFile twice. Your openOrCreateDatabase() should be called for old_sqliteFile, not databaseFile.

    Here is a method that will replace an unencrypted database file with an encrypted replacement:

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

提交回复
热议问题