Realm Swift iOS - securely delete and re-enter encrypted Kingdom

Does Realm Swift have a way to safely delete and create a new encrypted Realm file with a new key (but with the same name)?

My use case: when a user exits my application, I delete the encrypted .realm file, as the encryption key will also be deleted:

static func deleteRealm() { let configuration = Realm.Configuration() let path = NSURL.fileURLWithPath(configuration.path!) .URLByDeletingLastPathComponent? .URLByAppendingPathComponent("encrypted.realm") .path! if NSFileManager.defaultManager().fileExistsAtPath(path) { // Delete realm try! NSFileManager.defaultManager().removeItemAtPath(path) } } } 

(Unfortunately, calling realm.deleteAll() will not be sufficient, as there is a new key)

But when another user logs in immediately after logging out, and I try to reinitialize the encrypted Realm database with a new key, for example:

 static func intializeRealm() -> Realm! { let realmKey = generateSecureRealmKey() var configuration = Realm.Configuration() configuration.path = RealmDB.getRealmPath() configuration.encryptionKey = NSData(bytes: realmKey, length: realmKey.count) return try! Realm(configuration: configuration) } 

I get this exception:

  *** Terminating app due to uncaught exception 'RLMException', reason: 'Realm at path '****/encrypted.realm' already opened with different encryption key' 

It seems that the old configuration cache is still in use (as the file name is the same), although the scope file has been deleted.

The autoreleasepool encryption application for Realm Swift uses autoreleasepool to get around this, but this is not possible for a larger application. Or that? Should I surround all areas of use with autoreleasepool ?

+6
source share
1 answer

Before you can delete an existing Realm database or create a new one with a new encryption key in the same way, you need to make sure that all Realm accessors are closed. But, as you point out, this can be difficult to achieve in a larger application. The easiest way is probably to use a new file path. For this reason, I recommend putting the deletion of the actual database on the next application launch. You could achieve this by saving the path to the currently used Realm and deleting all other .realm files and all their supporting files in the same directory.

+1
source

All Articles