我正在试图弄清楚如何将加密应用于现有的未加密领域db?
从头开始设置加密领域很简单 - 只需提供密钥:
.encryptionKey(getRealmKey())
但是我的应用程序已经在野外,我希望能够继续使用所有现有数据。
到目前为止,这是一个天真的实现(崩溃与“引起:java.lang.IllegalArgumentException:目标文件不能存在”:
@Provides
public Realm realm(RealmConfiguration realmConfiguration) {
Realm realm = Realm.getInstance(realmConfiguration);
File encryptedFile = new File(context.getFilesDir(), "encrypted_realm");
realm.writeEncryptedCopyTo(encryptedFile, getRealmKey());
return realm;
}
@Provides
@Singleton
public RealmConfiguration realmConfiguration() {
Realm.init(context);
RealmConfiguration config = new RealmConfiguration.Builder()
.name("db")
.schemaVersion(7)
.migration(new AppRealmMigration())
.build();
return config;
}
private byte[] getRealmKey() {
return new byte[64];
}
答案 0 :(得分:3)
这应该有效。如果需要,它将检测旧Realm并将其复制为加密副本:
public Realm getInstance() {
RealmConfiguration newConfig = new RealmConfiguration.Builder()
.name("encrypted.realm") // Different name than old
.encryptionKey(getKey())
.build();
// If new file exist, assume it has already been migrated
File newRealmFile = new File(newConfig.getPath());
if (newRealmFile.exists()) {
return Realm.getInstance(newConfig);
} else {
// Migrate old Realm and delete old
RealmConfiguration old = new RealmConfiguration.Builder().build();
Realm realm = Realm.getInstance(old);
realm.writeEncryptedCopyTo(newRealmFile, getKey());
realm.close();
Realm.deleteRealm(old);
return Realm.getInstance(newConfig);
}
}