Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Realm Encryption Example

Tags:

android

realm

I have created Realm Encryption Example project source from following link https://github.com/realm/realm-java/tree/master/examples/encryptionExample/src/main/java/io/realm/examples/encryptionexample .When i run the project without any change in the code, it runs without error.but i comment the following line in source

Realm.deleteRealm(realmConfiguration);

because no need to delete old file for me. then i start the application.it throws error java.lang.IllegalArgumentException: Illegal Argument :Invalid Format of Realm File.

How can i read Realm file with same encryption key.

Source Code:

    package io.realm.examples.encryptionexample;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import java.security.SecureRandom;

import io.realm.Realm;
import io.realm.RealmConfiguration;

public class EncryptionExampleActivity extends Activity {

    public static final String TAG = EncryptionExampleActivity.class.getName();

    private Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 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 realmConfiguration = new RealmConfiguration.Builder(this)
                .encryptionKey(key)
                .build();

        // Start with a clean slate every time
        Realm.deleteRealm(realmConfiguration);

        // Open the Realm with encryption enabled
        realm = Realm.getInstance(realmConfiguration);

        // Everything continues to work as normal except for that the file is encrypted on disk
        realm.beginTransaction();
        Person person = realm.createObject(Person.class);
        person.setName("Happy Person");
        person.setAge(14);
        realm.commitTransaction();

        person = realm.where(Person.class).findFirst();
        Log.i(TAG, String.format("Person name: %s", person.getName()));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close(); // Remember to close Realm when done.
    }
}

Thanks in Advance.

like image 900
user3572524 Avatar asked Jul 10 '15 10:07

user3572524


1 Answers

I had the same problem. Just change the name of your file like this:

RealmConfiguration config = new RealmConfiguration.Builder(getActivity().getBaseContext())
            .name("myrealm_designtv.realm")
            .encryptionKey(loadkeyStore())
            .build();
Realm.setDefaultConfiguration(config);

And also change your key for the encryption it is not the right way to do it. Use a keystore. Here is the tutorial that I used http://www.androidauthority.com/use-android-keystore-store-passwords-sensitive-information-623779/ I can give you my loadkeyStore() function if you need more help (I didn't do it because it is not the question here).

/////////////////Here my laodKeyStore function ///////////

public byte[] loadkey(Context context) {


    byte[] content = new byte[64];
    try {
        if (ks == null) {
            createNewKeys(context);
        }

        ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);

         content= ks.getCertificate(ALIAS).getEncoded();
        Log.e(TAG, "key original :" + Arrays.toString(content));
    } catch (KeyStoreException | CertificateException | IOException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    content = Arrays.copyOfRange(content, 0, 64);
    return content;
}

/* And you will need createNewKeys function too */

public void createNewKeys(Context context) throws KeyStoreException {

    firstloadKeyStore();
    try {
        // Create new key if needed
        if (!ks.containsAlias(ALIAS)) {
            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            end.add(Calendar.YEAR, 1);
            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                    .setAlias(ALIAS)
                    .setSubject(new X500Principal("CN=Sample Name, O=Android Authority"))
                    .setSerialNumber(BigInteger.ONE)
                    .setStartDate(start.getTime())
                    .setEndDate(end.getTime())
                    .build();
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
            generator.initialize(spec);

            KeyPair keyPair = generator.generateKeyPair();
            Log.e(TAG, "key :" + keyPair.getPrivate().getEncoded().toString());

        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}
like image 183
Dagnogo Jean-François Avatar answered Oct 19 '22 08:10

Dagnogo Jean-François