Docs Menu

Encrypt a Realm - Swift SDK

On this page

  • Overview
  • Considerations
  • Storing & Reusing Keys
  • Performance Impact
  • Encryption and Realm Sync
  • Multiple Processes
  • Example

You can encrypt the realm database file on disk with AES-256 + SHA-2 by supplying a 64-byte encryption key when opening a realm.

Realm transparently encrypts and decrypts data with standard AES-256 encryption using the first 256 bits of the given 512-bit encryption key. Realm uses the other 256 bits of the 512-bit encryption key to validate integrity using a hash-based message authentication code (HMAC).


Do not use cryptographically-weak hashes for realm encryption keys. For optimal security, we recommend generating random rather than derived encryption keys.

You must pass the same encryption key when opening the realm again. Apps should store the encryption key in the Keychain so that other apps cannot read the key.

Typically, reads and writes on encrypted realms can be up to 10% slower than unencrypted realms.

You can encrypt a synced realm. MongoDB Realm only encrypts the data on the device and stores the data unencrypted in your MongoDB Atlas data source.

Realm forbids opening the same encrypted realm from multiple processes. Attempting to do so will throw the error: "Encrypted interprocess sharing is currently unsupported."

If multiple processes need to access a realm simultaneously, use an unencrypted realm. Encrypted realms cannot be accessed by multiple processes at the same time.

As an alternative, you can store data that you want to encrypt as NSData properties on realm objects. Then, you can encrypt and decrypt individual fields.

One possible tool to encrypt and decrypt fields is Apple's CryptoKit framework. You can use Swift Crypto to simplify app development with CryptoKit.

The following code demonstrates how to generate an encryption key and open an encrypted realm:

The following Swift example demonstrates how to store and retrieve a generated key from the Keychain:

// Retrieve the existing encryption key for the app if it exists or create a new one
func getKey() -> Data {
// Identifier for our keychain entry - should be unique for your application
let keychainIdentifier = "io.Realm.EncryptionExampleKey"
let keychainIdentifierData = String.Encoding.utf8, allowLossyConversion: false)!
// First check in the keychain for an existing key
var query: [NSString: AnyObject] = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: keychainIdentifierData as AnyObject,
kSecAttrKeySizeInBits: 512 as AnyObject,
kSecReturnData: true as AnyObject
// To avoid Swift optimization bug, should use withUnsafeMutablePointer() function to retrieve the keychain item
// See also:
var dataTypeRef: AnyObject?
var status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
// swiftlint:disable:next force_cast
return dataTypeRef as! Data
// No pre-existing key from this application, so generate a new one
// Generate a random encryption key
var key = Data(count: 64)
key.withUnsafeMutableBytes({ (pointer: UnsafeMutableRawBufferPointer) in
let result = SecRandomCopyBytes(kSecRandomDefault, 64, pointer.baseAddress!)
assert(result == 0, "Failed to get random bytes")
// Store the key in the keychain
query = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: keychainIdentifierData as AnyObject,
kSecAttrKeySizeInBits: 512 as AnyObject,
kSecValueData: key as AnyObject
status = SecItemAdd(query as CFDictionary, nil)
assert(status == errSecSuccess, "Failed to insert the new key in the keychain")
return key
// ...
// Use the getKey() function to get the stored encryption key or create a new one
var config = Realm.Configuration(encryptionKey: getKey())
do {
// Open the realm with the configuration
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)")
←  Threading - Swift SDKCompact a Realm - Swift SDK →
Give Feedback
© 2022 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.