Converting sqlite to encrypted database:

后端 未结 2 1359
孤独总比滥情好
孤独总比滥情好 2021-02-11 02:12

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:31

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

提交回复
热议问题