2017-01-16 124 views
0

我嘗試運行SQLCipher over存在未加密的數據庫。SQLCipher Android,爲未加密的數據庫設置密鑰

我使用的方法似乎正在工作,但沒有加密與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

運行有沒有什麼解決辦法嗎?

回答

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