Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating/changing Realm encryption key

Tags:

android

realm

I have encrypted Realm database in my application. I would like to change the encryption key. Is the proper way to do this making a copy of the Realm file with new encryption key or is there some another option available?

Thanks.

like image 381
Niko Avatar asked Dec 09 '15 08:12

Niko


1 Answers

Yes, you have to make a copy of the Realm file with the new encryption key. The method is called writeEncryptedCopyTo(): https://realm.io/docs/java/latest/api/io/realm/Realm.html#writeEncryptedCopyTo-java.io.File-byte:A-

Something like the below should work:

RealmConfiguration config1 = new RealmConfiguration.Builder(context)
  .name("old-name")
  .encryptionKey(getOldKey())
  .build()

Realm realm = Realm.getInstance(config1);
realm.writeEncryptedCopyTo(new File(context.getFilesDir(), "new-name"), getNewKey());
realm.close();

RealmConfiguration config2 = new RealmConfiguration.Builder(context)
  .name("new-name")
  .encryptionKey(getNewKey())
  .build()
like image 196
Christian Melchior Avatar answered Nov 11 '22 09:11

Christian Melchior