Navigation

Encrypt a Realm

Overview

You can the 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).

Considerations

Storing & Reusing Keys

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

Performance Impact

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

Encryption and Realm Sync

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.

Example

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

// Generate a key
// IMPORTANT! This is a silly way to generate a key. It is also never stored.
// For proper key handling please consult:
// * https://developer.android.com/training/articles/keystore.html
// * http://nelenkov.blogspot.dk/2012/05/storing-application-secrets-in-androids.html
val key = ByteArray(64)
SecureRandom().nextBytes(key)
val config = RealmConfiguration.Builder()
    .encryptionKey(key)
    .build()

// Open the encrypted realm
val realm = Realm.getInstance(config)
// Generate a key
// IMPORTANT! This is a silly way to generate a key. It is also never stored.
// For proper key handling please consult:
// * https://developer.android.com/training/articles/keystore.html
// * http://nelenkov.blogspot.dk/2012/05/storing-application-secrets-in-androids.html
byte[] key = new byte[64];
new SecureRandom().nextBytes(key);
RealmConfiguration config = new RealmConfiguration.Builder()
        .encryptionKey(key)
        .build();

// Open the encrypted realm
Realm realm = Realm.getInstance(config);