【发布时间】:2017-08-20 09:56:31
【问题描述】:
我正在尝试使用 writeCopy(toFile:, encryptionKey:) 更改我的 Realm 数据库的加密密钥,如下所示:
public static func updateEncryption(forNewKey newKey: String, withOldKey oldKey: String, completion: (() -> Void)) {
let defaultURL = Backup.realmContainerURL
let defaultParentURL = defaultURL.deletingLastPathComponent()
let compactedURL = defaultParentURL.appendingPathComponent("default-compact.realm")
let oldKeyData = oldKey.pbkdf2SHA256(keyByteCount: 64)
let newKeyData = newKey.pbkdf2SHA256(keyByteCount: 64)
let oldEncryptionConfig = Realm.Configuration(fileURL: Backup.realmContainerURL, encryptionKey: oldKeyData)
autoreleasepool {
do {
let oldRealm = try Realm(configuration: oldEncryptionConfig)
try oldRealm.writeCopy(toFile: compactedURL, encryptionKey: newKeyData)
oldRealm.invalidate()
try FileManager.default.removeItem(at: defaultURL)
try FileManager.default.moveItem(at: compactedURL, to: defaultURL)
completion()
} catch {
fatalError(error.localizedDescription)
}
}
}
之后,我正在使用以下方法在我的应用中重新加载数据:
public static func loadAll(withEncryptionKey encryptionKey: String) -> [Backup] {
do {
let key = encryptionKey.pbkdf2SHA256(keyByteCount: 64)
let encryptionConfig = Realm.Configuration(fileURL: Backup.realmContainerURL, encryptionKey: key)
let realm = try Realm(configuration: encryptionConfig)
let allObjects = realm.objects(Backup.self).sorted(byKeyPath: "date", ascending: false)
return allObjects.map({ $0 })
} catch {
fatalError(error.localizedDescription)
}
}
所以我将loadAll(withEncryptionKey:) 函数与新密钥一起使用,但在let realm = try Realm(configuration: encryptionConfig) 应用程序在RLMRealm.mm 文件第347 行崩溃:@throw RLMException(@"Realm at path '%s' already opened with different encryption key", config.path.c_str()); 与控制台日志libc++abi.dylib: terminating with uncaught exception of type NSException。
所以看起来writeCopy(toFile:, encryptionKey:) 没有更改encryptionKey,或者Realm 仍然看到旧的.realm 文件。但有趣的是,在重新打开我的应用程序后,loadAll(withEncryptionKey:) 使用新的加密密钥加载数据没有任何问题。
如何解决这个问题呢?如何更改加密密钥仍然可以使用应用程序?
非常感谢您的帮助。
【问题讨论】: