Realm database decryption failed
Asked Answered
A

1

0

Question : When I try to open encrypted realm file in Realm Browser (windows) and it gives me following message.

Either this is not a Realm file or it's encrypted.

Enter: 128-character hex-encoded encryption key

Important - I am closing my realm before saving on disk.

Code

RealmConfiguration config = new RealmConfiguration.Builder()
            .name("w5uyqFyEDEK_OCWyl4123aa77")
            .schemaVersion(2)
            .encryptionKey(myClassObject.getRealmKey())
            .deleteRealmIfMigrationNeeded()
            .build();

Methods

 public byte[] getRealmKey() {
    byte[] key;
    String savedKey = getStringFromPrefs(KEY);
    if (savedKey.isEmpty()) {
        key = generateKey();
        String keyString = encodeToString(key);
        saveStringToPrefs(keyString);
    } else {
        key = decodeFromString(savedKey);
    }
    return key;
}



 private void saveStringToPrefs(String aKeyString) {
    pref.edit().putString(KEY, aKeyString).apply();
}

private String encodeToString(byte[] aKey) {
    AppLogger.d("Encoding Key: %s", Arrays.toString(aKey));
    return Base64.encodeToString(aKey, Base64.DEFAULT);
}

private byte[] decodeFromString(String aSavedKey) {
    byte[] decoded = Base64.decode(aSavedKey, Base64.DEFAULT);
    AppLogger.d("Decoded Key: ", Arrays.toString(decoded));
    return decoded;
}

private byte[] generateKey() {
    byte[] key = new byte[64];
    new SecureRandom().nextBytes(key);
    return key;
}

I have tried to open encrypted realm file using key stored in preference and byte[] decodedKey but still I am not able to open realm file.

Am I missing something here?

Admix answered 27/11, 2017 at 6:34 Comment(0)
T
3

You need to Hex encode your encryption key, not Base64 encode it.

You can see how to do it here: https://github.com/realm/realm-java/pull/5571

Torino answered 27/11, 2017 at 9:41 Comment(1)
is there a way to catch the error, Realm file decryption failed. There might be a great chance when the decryption key is not available and the Realm throws this error. How to catch this error and delete the existing Realm and create a new one with the new Encryption Key. For testing, I have stored the Realm Key in the Shared Preferences and getting the encryption key in the Application Class before i initialize the Realm Object. But sometimes, the key i am getting is different or null or empty and the Realm throws the error. How to handle this situation?Equally

© 2022 - 2024 — McMap. All rights reserved.