我想知道如何将加密应用于现有的未加密 Realm 数据库?
从头开始设置加密 Realm 很容易 - 只需在以下位置提供 key :
.encryptionKey(getRealmKey())
但我的应用程序已经投入使用,我希望它能继续使用所有现有数据。
到目前为止,这是它的一个简单实现(因“Caused by: java.lang.IllegalArgumentException: The destination file must not exist”而崩溃):
@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];
}
最佳答案
这应该有效。它将检测旧的 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);
}
}
关于android - 将预先存在的(未加密的) Realm 数据库迁移到新的加密 Realm 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43523965/