android - 将预先存在的(未加密的) Realm 数据库迁移到新的加密 Realm 数据库

标签 android realm

我想知道如何将加密应用于现有的未加密 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/

相关文章:

android - 无法从 Realm 对象检索字段值,调试器中的值为空

android - 使用 stripe_ payment 时 Flutter Android 应用程序在启动时崩溃

android - 删除应用内结算测试 ID 的历史记录以进行重新测试

android - 导航 Controller fragment 泄漏

java - Realm 异步任务

java - 为什么我在尝试删除 Realm 中的对象时收到 ArrayIndexOutOfBoundsException?

android - 带有 Beacons MAC 的 Google Awareness API

java - IMAGE_CAPTURE Intent 永远不会返回到 onActivityResult(int, int, Intent);

swift - 如何初始化 Realm 列表?

android - 将 Kotlin ByteArray 保存到 Realm 中