Class SecurePreferenceDataStore

  • All Implemented Interfaces:

    
    public final class SecurePreferenceDataStore
    extends PreferenceDataStore
                        

    A PreferenceDataStore implementation encrypts contents using 256-bit AES encryption, and is provided to the Preference framework via setPreferenceDataStore.

    This class can be used to replace the default SharedPreferences and provides an extra layer of application data protection.

    You must create and open the store with an encryption key before you can interact with it. It is recommended to use EncryptionUtil to obtain the encryption key. If this is the first time store is being opened and null is provided, an encryption key will be generated transparently and will be used for subsequent opens.
    
        final String storeName = "myPreferenceStore";
        final byte[] encryptionKey = EncryptionUtil.getEncryptionKey("aliasForPreferenceStore",
            myPasscode);
        SecurePreferenceDataStore store = null;
    
        try {
            store = new SecurePreferenceDataStore(
                            androidContext, // Android application context.
                            storeName,      // Store name.
                            encryptionKey); // Store's encryption key; auto-generated if null.
        } catch (OpenFailureException ex) {
            logger.error("An error occurred while opening the preference data store.", ex);
        }
     

    The following preference value types are supported:

    • String
    • Integer
    • Long
    • Float
    • Boolean
    • Any Set implementation that is Serializable

    You can use the appropriate put and get methods to add and retrieve preference values to/from the data store.

    
        try {
            // Adds preferences to the store.
            store.putInt("integerKey1", 58);
            store.putString("StringKey1", "A String value");
            store.putFloat("floatKey1", 9.8F);
            store.putLong("longKey1", 9223372036854775000L);
            store.putBoolean("booleanKey1", true);
    
            // Adds a set of values as a preference to the store.
            // 'stringSet' is a HashSet<String> that contains values.
            store.putStringSet(stringSetKey, stringSet);
    
            // Retrieves existing values.
            int intValue = store.getInt("integerKey1", 0);
            String stringValue = store.getString("StringKey1", "default String if not found");
            float floatValue = store.getFloat("floatKey1", 0.2F);
            long longValue = store.getLong("longKey1", 9223372036854775023L);
            boolean booleanValue = store.getBoolean("booleanKey1", false);
        } catch (BackingStoreException ex) {
            logger.error("Failed to add/retrieve preference.", ex);
        }
     
    You can remove preferences one at a time or remove all at once.
    
        try {
            // Removes preferences one at a time.
            store.remove("booleanKey1");
            store.remove("longKey1");
    
            // Removes all existing preferences.
            store.removeAll();
        } catch (BackingStoreException ex) {
            logger.error("Failed to remove preference.", ex);
        }
     
    You can change the encryption of the underlying persistence store when the store is in open state.
    
        store.changeEncryptionKey(newEncryptionKey);
    
    When you finish CRUD operations on the store, close the SecurePreferenceDataStore to relinquishes any resources it has acquired during its operations.
    
        store.close();
     
    You may want to remove the persistence store in some occasions. Note that after the persistence store is removed, any further operation performed on the instance will cause FileMissingException.
    
        store.deleteStore(context); // The store instance will not be usable after this method!
    
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
    • Field Summary

      Fields 
      Modifier and Type Field Description
    • Constructor Summary

      Constructors 
      Constructor Description
      SecurePreferenceDataStore(Context context, String storeName, Array<byte> encryptionKey) Constructs a secure PreferenceDataStore.
    • Enum Constant Summary

      Enum Constants 
      Enum Constant Description
    • Method Summary

      Modifier and Type Method Description
      void changeEncryptionKey(@Nullable() Array<byte> newEncryptionKey) Changes the encryption key of the store while the store is opened (close is not yet called).
      void deleteStore(@NonNull() Context context) Deletes the underlying persistence store file.
      void putString(@NonNull() String key, @Nullable() String value) Sets a String value to data store.
      void putStringSet(@NonNull() String key, @Nullable() Set<String> values) Sets a set of Strings to the data store.
      void putInt(@NonNull() String key, int value) Sets an integer value to data store.
      void putLong(@NonNull() String key, long value) Sets a long value to data store.
      void putFloat(@NonNull() String key, float value) Sets a float value to data store.
      void putBoolean(@NonNull() String key, boolean value) Sets a boolean value to data store.
      String getString(@NonNull() String key, @Nullable() String defValue) Retrieves a String value from the data store.
      Set<String> getStringSet(@NonNull() String key, @Nullable() Set<String> defValues) Retrieves a set of Strings from the data store.
      int getInt(@NonNull() String key, int defValue) Retrieves an integer value from the data store.
      long getLong(@NonNull() String key, long defValue) Retrieves a long value from the data store.
      float getFloat(@NonNull() String key, float defValue) Retrieves a float value from the data store.
      boolean getBoolean(@NonNull() String key, boolean defValue) Retrieves a boolean value from the data store.
      void remove(@NonNull() String key) Removes a preference from the data store.
      void removeAll() Removes all preferences from the data store.
      void close() Closes the store and relinquishes all resources acquired during its operations .
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • SecurePreferenceDataStore

        SecurePreferenceDataStore(Context context, String storeName, Array<byte> encryptionKey)
        Constructs a secure PreferenceDataStore.
        Parameters:
        context - Android application context
        storeName - a non-empty name of the store that can only contain -, _, a-z, A-Z, 0-9 and ..
        encryptionKey - the key which is used to encrypt/decrypt the store.
    • Method Detail

      • changeEncryptionKey

         void changeEncryptionKey(@Nullable() Array<byte> newEncryptionKey)

        Changes the encryption key of the store while the store is opened (close is not yet called).

        Parameters:
        newEncryptionKey - new encryption key.
      • deleteStore

         void deleteStore(@NonNull() Context context)

        Deletes the underlying persistence store file. Note that this instance will not be usable after calling this method, and any operation performed on the instance will get FileMissingException.

        Parameters:
        context - Android application context
      • putString

         void putString(@NonNull() String key, @Nullable() String value)

        Sets a String value to data store.

        Parameters:
        key - the name of the preference to modify
        value - the new value for the preference
      • putStringSet

         void putStringSet(@NonNull() String key, @Nullable() Set<String> values)

        Sets a set of Strings to the data store.

        Parameters:
        key - the name of the preference to modify
        values - the set of new values for the preference
      • putInt

         void putInt(@NonNull() String key, int value)

        Sets an integer value to data store.

        Parameters:
        key - the name of the preference to modify
        value - the new value for the preference
      • putLong

         void putLong(@NonNull() String key, long value)

        Sets a long value to data store.

        Parameters:
        key - the name of the preference to modify
        value - the new value for the preference
      • putFloat

         void putFloat(@NonNull() String key, float value)

        Sets a float value to data store.

        Parameters:
        key - the name of the preference to modify
        value - the new value for the preference
      • putBoolean

         void putBoolean(@NonNull() String key, boolean value)

        Sets a boolean value to data store.

        Parameters:
        key - the name of the preference to modify
        value - the new value for the preference
      • getString

        @Nullable() String getString(@NonNull() String key, @Nullable() String defValue)

        Retrieves a String value from the data store.

        Parameters:
        key - the name of the preference to retrieve
        defValue - the value to return if this preference does not exist in the data store
      • getStringSet

        @Nullable() Set<String> getStringSet(@NonNull() String key, @Nullable() Set<String> defValues)

        Retrieves a set of Strings from the data store.

        Parameters:
        key - the name of the preference to retrieve
        defValues - the values to return if this preference does not exist in the storage
      • getInt

         int getInt(@NonNull() String key, int defValue)

        Retrieves an integer value from the data store.

        Parameters:
        key - the name of the preference to retrieve
        defValue - the value to return if this preference does not exist in the data store
      • getLong

         long getLong(@NonNull() String key, long defValue)

        Retrieves a long value from the data store.

        Parameters:
        key - the name of the preference to retrieve
        defValue - the value to return if this preference does not exist in the data store
      • getFloat

         float getFloat(@NonNull() String key, float defValue)

        Retrieves a float value from the data store.

        Parameters:
        key - the name of the preference to retrieve
        defValue - the value to return if this preference does not exist in the data store
      • getBoolean

         boolean getBoolean(@NonNull() String key, boolean defValue)

        Retrieves a boolean value from the data store.

        Parameters:
        key - the name of the preference to retrieve
        defValue - the value to return if this preference does not exist in the data store
      • remove

         void remove(@NonNull() String key)

        Removes a preference from the data store.

        Parameters:
        key - the name of the preference to remove
      • removeAll

         void removeAll()

        Removes all preferences from the data store.

      • close

         void close()

        Closes the store and relinquishes all resources acquired during its operations . Note that once the store is closed, no operations are allowed.