我在我的应用程序中使用realm数据库,目前在Application
类我正在使用默认配置初始化领域,并且我正在使用Realm.getDefaultConfiguration()
来查询/保存数据。
现在我想加密数据库,我按照以下方式做了
RealmConfiguration config = new RealmConfiguration.Builder()
.encryptionKey(getKeyFunction())
.migration(new MyMigration())
.build();
Realm.setDefaultConfiguration(config);`
但是当我尝试访问Realm.getDefaultConfiguration()
时,我收到Invalid format of Realm File
错误。
我做错了什么?
答案 0 :(得分: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()));