2016-10-04 23 views
1

我在我的應用程序中使用了領域數據庫,並且當前在Application類中,我使用默認配置初始化領域並且在使用Realm.getDefaultConfiguration()來查詢/保存數據的應用程序中處處都有。如何使用加密密鑰設置RealmDefaultConfiguration

現在我想加密數據庫,我做如下

RealmConfiguration config = new RealmConfiguration.Builder() 
      .encryptionKey(getKeyFunction()) 
      .migration(new MyMigration()) 
      .build(); 
Realm.setDefaultConfiguration(config);` 

但是,當我嘗試訪問Realm.getDefaultConfiguration()我得到錯誤。

我在做什麼錯?

+0

你需要爲你的加密做用於解密相同的密鑰:這意味着你必須記住,你使用首先創建加密的境界文件 – EpicPandaForce

回答

0

這是我的工作代碼。我已經在我的樣本項目中測試了這個

// Generate a key 
    // IMPORTANT! This is a silly way to generate a key. It is also never stored. 
    // For proper key handling please consult: 
    // * https://developer.android.com/training/articles/keystore.html 
    // * http://nelenkov.blogspot.dk/2012/05/storing-application-secrets-in-androids.html 
    Realm.init(this); 
    byte[] key = new byte[64]; 
    new SecureRandom().nextBytes(key); 
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder() 
      .encryptionKey(key) 
      .build(); 

    // Start with a clean slate every time 
    Realm.deleteRealm(realmConfiguration); 

    Realm.setDefaultConfiguration(realmConfiguration); 
    // Open the Realm with encryption enabled 
    realm = Realm.getDefaultInstance(); 
    //realm = Realm.getInstance(realmConfiguration); 
    // Everything continues to work as normal except for that the file is encrypted on disk 
    realm.executeTransaction(new Realm.Transaction() { 
     @Override 
     public void execute(Realm realm) { 
      Person person = realm.createObject(Person.class); 
      person.setName("Happy Person"); 
      person.setAge(14); 
     } 
    }); 

    Person person = realm.where(Person.class).findFirst(); 
    Log.i(TAG, String.format("Person name: %s", person.getName())); 
+0

我關心的是如何能在關鍵我將其設置爲默認配置,並使用Realm.getDefaultInstance()訪問Realm實例。執行此操作我需要在配置時提供一次加密密鑰。 –

+0

編輯我的答案。請看看這個。 –