Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to catch `RealmFileException: Realm file decryption failed` exception

Tags:

swift

realm

I'm relying on an encrypted realm to store certain data in an app written in Swift. Sometimes I face a situation where I delete a given realm and create a new one to ensure that no data will persist between certain states.

I keep track of encryption keys myself, so there is a risk that I unintentionally attempt to decrypt a realm with a wrong encryption key, which raises the following exception:

libc++abi.dylib: terminating with uncaught exception of type realm::RealmFileException: Unable to open a realm at path '/path/to/private.realm': Realm file decryption failed.

Since this means that I have lost the original encryption key, essentially leaving this particular realm useless, I'd like to be able to delete the realm file and start over instead of crashing.

I create the realm as suggested by the docs:

do {
  var configuration = Realm.Configuration.defaultConfiguration
  configuration.encryptionKey = ...
  try Realm(configuration: configuration)
}
catch let error {

}

I've tried this and similar approaches to catch the NSException and return it to be handled by Swift code, but there doesn't seem to be an straight forward way to achieve this. Is it impossible, or am I approaching this incorrectly?

like image 422
Kasper Munck Avatar asked Sep 13 '25 17:09

Kasper Munck


2 Answers

Your code should work. If the encryption key is wrong, entered the catch block. Then you can delete existing file and re-create Realm. Like the following:

var configuration = Realm.Configuration.defaultConfiguration
configuration.encryptionKey = getKey()
do {
    let realm = try Realm(configuration: configuration)
    ...
}
catch {
    try! NSFileManager().removeItemAtURL(configuration.fileURL!)
    let realm = try! Realm(configuration: configuration)
    ...
}

If you cannot catch the wrong encryption error, it might be using old Realm.framework. Please update the latest version of Realm.

like image 100
kishikawa katsumi Avatar answered Sep 16 '25 09:09

kishikawa katsumi


It turns out the problem was caused by a bug in Realm, where deleteRealmIfMigrationNeeded = true when using encryption, caused the exception to be thrown, but impossible to catch.

From my (very helpful) correspondence with kishikawa katsumi:

The problem that unable to catch error is due to deleteRealmIfMigrationNeeded is true. It changes code flow unintentionally. It seems Realm's bug. We will fix soon.

For now, the only thing to do in my case is to set deleteRealmIfMigrationNeeded = false and handle this case manually. I have filed this issue to Realm.

Update: The issue should be resolved with this commit.

like image 27
Kasper Munck Avatar answered Sep 16 '25 07:09

Kasper Munck