loading words...

Mar 17, 2019 16:38:17

Realm Encrypted Database - iOS

by @valentino | 207 words | 60🔥 | 358💌

Valentino Urbano

Current day streak: 60🔥
Total posts: 358💌
Total words: 170604 (682 pages 📄)


At times you need more security than usual for your database. In these cases, you might want to have your whole database encrypted on the device. I'd argue that it is a good practice to do so even if your apps' information is not that important. It doesn't cost much (at least if you're using Realm) in term of development time, but it is a huge burden off your shoulders... With Realm, it is really easy to do so. First, you need to generate an encryption key securely and store it safely (I store them in the Keychain).

We are going to assume that you already know how to add and remove data to and from the keychain. If you don't you can check out Apple's official documentation on it.

Open the file where you initialize the database and right before you set the "Realm.Configuration" object add the following:

```

if !KeychainWrapper.hasEncryptionKey() {

var keyData = Data(count: 64)//generate key

let count = keyData.count

let _ = keyData.withUnsafeMutableBytes {mutableBytes in

SecRandomCopyBytes(kSecRandomDefault, count, mutableBytes)//make it random

}

try? KeychainWrapper.addEncryptionKey(encryptionKey: keyData)//save it

}

guard let key = try? KeychainWrapper.getEncryptionKey() else {//get the saved key

log.error("error getting encryption key")

fatalError()

}

let config = Realm.Configuration(

fileURL:dbPath,

encryptionKey: key,//use the key to encrypt the db

```


Originally published at www.valentinourbano.com

contact: email - twitter / Terms / Privacy