Android Realm Encryption Example

I created the project source code for the Realm Encryption example from the 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 code changes, it runs without errors. but I will comment on the next line in the source

Realm.deleteRealm(realmConfiguration);

because I do not need to delete the old file. then I run application.it throws a java.lang.IllegalArgumentException error: Invalid argument: invalid Realm file format.

How can I read a Realm file with the same encryption key.

Source:

    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 at Advance.

+4
source share
1 answer

. :

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

, . . , http://www.androidauthority.com/use-android-keystore-store-passwords-sensitive-information-623779/ loadkeyStore(), ( , ).

///////////////// laodKeyStore///////////

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;
}

/* createNewKeys */

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));
    }
}
+6

All Articles