How to Encrypt Relam data


#1

I have created some models and saved into Realm. Now i want to do encryption for entire data.


(Zsolt Jandzso) #2

You can find the documentation here: https://realm.io/docs/swift/latest/#encryption

Sample app here: https://github.com/realm/realm-cocoa/tree/master/examples/ios/swift/Encryption


#3

Hi freeubi,

My code snippet,

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

    let config = Realm.Configuration (
        
        // Set the new schema version. This must be greater than the previously used
        // version (if you've never set a schema version before, the version is 0).
        schemaVersion: 1,
        
        migrationBlock: { migration, oldSchemaVersion in
            // We haven’t migrated anything yet, so oldSchemaVersion == 0
            if (oldSchemaVersion < 1) {
                // Nothing to do!
                // Realm will automatically detect new properties and removed properties
                // And will update the schema on disk automatically
            }
    })
    
    // Tell Realm to use this new configuration object for the default Realm
    Realm.Configuration.defaultConfiguration = config


    // Generate a random encryption key
    var key = Data(count: 64)
    _ = key.withUnsafeMutableBytes { bytes in
        SecRandomCopyBytes(kSecRandomDefault, 64, bytes)
    }
    
    // Open the encrypted Realm file
    let newConfig = Realm.Configuration(encryptionKey: key)
    do {
        let realm = try Realm(configuration: newConfig)
        // Use the Realm as normal
        let persons = realm.objects(Person.self).filter("name contains 'Nivru'")
    } catch let error as NSError {
        // If the encryption key is wrong, `error` will say that it's an invalid database
        fatalError("Error opening realm: \(error)")
    }
  
    return true
}

#4

but i got below errors,
Fatal error: Error opening realm: Error Domain=io.realm Code=2 "Unable to open a realm at path…

Realm file decryption failed Path:." UserInfo={Error Code=2,

so can you please tell whats wrong with my code


(Zsolt Jandzso) #5

The issue is exactly what the error said.
If you generate a new encryption key every run, you cant open the previous realm…


#6

Hi freeubi,

My encryption method is below and i am calling it from viewDidLoad. But problem is i can open my default.realm file directly instead of  asking key in Realm Studio.

func encryptRealm() {

    var encryKey : String?
    
    let defaults = UserDefaults.standard
    
    if defaults.value(forKey: "encryptionKey") != nil {
        encryKey = defaults.value(forKey: "encryptionKey") as? String
    }
    else {
        print("Key value not present so create key...!!!")
        
        var key = Data(count: 64)
        _ = key.withUnsafeMutableBytes { bytes in
            SecRandomCopyBytes(kSecRandomDefault, 64, bytes)
        }
                    
        defaults.setValue(key, forKey: "encryptionKey")
        
        encryKey = defaults.value(forKey: "encryptionKey") as? String
        
    }
    
    let config = Realm.Configuration(encryptionKey: encryKey?.data(using: String.Encoding.utf8, allowLossyConversion: false))
   
    do {
        let realm = try Realm(configuration: config)
        // Use the Realm as normal
        
    } catch let error as NSError {
        // If the encryption key is wrong, `error` will say that it's an invalid database
        fatalError("Error opening realm: \(error)")
    }
    
}

I am new to Realm so please help me. Thanks in advance.