Encrypt a Realm - Java SDK
On this page
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).
Reads and writes on encrypted realms can be up to 10% slower than equivalent reads and writes to unencrypted realms.
You can encrypt a synced realm, but MongoDB Realm only encrypts the data on the device. MongoDB Realm stores the data unencrypted in your data source.
Store & Reuse Keys
To repeatedly access an encrypted realm, you must pass the same encryption key to RealmConfiguration.Builder.encryptionKey() each time you open the realm. Apps should store the encryption key in the Android KeyStore so that other apps cannot read the key. The following steps describe the recommended way to use the KeyStore for encryption with Realm:
Generate an asymmetric RSA key that Android can securely store and retrieve using the Android KeyStore.
NoteAndroid Version M and Above: Keystore SecurityVersions M and above require user PIN or fingerprint to unlock the KeyStore.
- Generate a symmetric key (AES) you can use to encrypt the realm.
- Encrypt the symmetric AES key using your private RSA key.
- Store the encrypted AES key on filesystem (in a
SharedPreferences
, for example).
When you need to use your encrypted realm:
- Retrieve your encrypted AES key.
- Decrypt your encrypted AES key using the public RSA key.
- Use the decrypted AES key in the
RealmConfiguration
to open the encrypted realm.
For an end-to-end example of storing and reusing encryption keys, see the store_password example project, which demonstrates the fingerprint API.
Do not use cryptographically-weak hashes for realm encryption keys. For optimal security, we recommend generating random rather than derived encryption keys.
Generate and Store an Encryption Key
The following code demonstrates how to securely generate and store an encryption key for a realm:
Access an Existing Encryption Key
The following code demonstrates how to access and decrypt a securely stored encryption key for a realm:
Open an Encrypted Realm
The following code demonstrates how to open an encrypted realm with the encryptionKey() method:
Accessing an Encrypted Realm from Multiple Process
Realm forbids opening the same encrypted realm from multiple processes. Attempting to do so will throw the error: "Encrypted interprocess sharing is currently unsupported."