Class SecureKeyValueStore

  • All Implemented Interfaces:
    java.lang.AutoCloseable

    
    public final class SecureKeyValueStore
     implements AutoCloseable
                        

    The SecureKeyValueStore is used to persist key-value pairs using an encrypted backing store. It uses String as the key type, and can store any values of the following types:

    • Boolean
    • Byte
    • Double
    • Float
    • Integer
    • Long
    • Short
    • String
    • byte[]
    • Any Object that implements Serializable interface
    You must instantiate the store and then open it with an encryption key. 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.
    
        byte[] myEncryptionKey = EncryptionUtil.getEncryptionKey("aliasForMyKeyValueStore", myPasscode);
        SecureKeyValueStore store = new SecureKeyValueStore(appContext, "myKeyValueStoreName");
        store.open(myEncryptionKey);
    
        // Or pass null for the store to generate the encryption key transparently.
        // store.open(null);
    
    A SecureKeyValueStore has void put(String key, T value) to add values of the supported types, and methods to retrieve different data types in an appropriate format:
    
        class Organization implements Serializable {
            private String name;
            private String id;
    
            public Organization() { super();}
            public Organization(String name, String id) {
                this.name = name;
                this.id = id;
            }
            public String getName() { return name; }
            public void setName(String name) { this.name = name; }
            public String getId() { return id; }
            public void setId(String id) { this.id = id; }
        }
    
        String orgId = "ORG_HR_1";
        Organization org = new Organization("Human Resource", orgId);
    
        try {
            store.put(orgId, org); // Adds an Organization object to the store.
        } catch (BackingStoreException | TypeConversionException ex) {
            logger.error("Failed to add Organization {}", orgId, ex);
        }
    
    You must use the appropriate method to retrieve the data from the key-value store by passing a String key:
    
        try {
            store.put("Integer value", 3);                  // Integer value.
            store.put("Double value", 3.5D);                // Double value.
            store.put("String value", "This is a String");  // String value.
            store.put("Int16Value", (short) 17);            // Short value.
            store.put("Int64Value", 41L);                   // Long value.
            store.put("FloatValue", 1.3F);                  // Float value.
    
            // Retrieves values with the appropriate get methods using the original keys.
            Integer intValue = store.getInt("Integer value");
            Double doubleValue = store.getDouble("Double value");
            String stringValue = store.getString("String value");
            Short shortValue = store.getInt16("Int16Value");
            Long longValue = store.getInt64("Int64Value");
            Float floatValue = store.getFloat("FloatValue");
        } catch (BackingStoreException | TypeConversionException ex) {
            logger.error("An error occurred during put/get operation,", ex);
        }
    
    You can use keys to retrieve the keys of existing entries:
    
        try {
            String[] keys = store.keys();
    
            for (String key : keys) {
                logger.debug("Retrieved key {}", key);
            }
        } catch (FileClosedException | BackingStoreException ex) {
            logger.error("Failed to retrieve all existing keys: ", ex);
        }
        
    You can remove one or all existing entries in the store:
    
        try {
            // Removes one entry using the key.
            store.remove("Int64Value");
    
            // Removes all existing entries.
            store.removeAll();
        } catch (FileClosedException | BackingStoreException ex) {
            logger.error("Failed to remove entry/entries.", ex);
        }
    
    You can change the encryption of the underlying persistence store when the store is in open state.
    
        store.changeEncryptionKey(newEncryptionKey);
    
    When you finish executing key-value store operations, close the SecureKeyValueStore to relinquishes any resources it has acquired during its operations:
    
        store.close();
    
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
    • Field Summary

      Fields 
      Modifier and Type Field Description
    • Constructor Summary

      Constructors 
      Constructor Description
      SecureKeyValueStore(Context context, String storeName) Constructs a Secure Key Value store.
    • Enum Constant Summary

      Enum Constants 
      Enum Constant Description
    • Method Summary

      Modifier and Type Method Description
      synchronized void open(@Nullable() Array<byte> encryptionKey) Opens the key value store with the encryption key.
      synchronized boolean isOpen() Checks if the store is open.
      synchronized void close() Closes the key value store to release system resources.
      synchronized int count() Returns the number of items in the key value store.
      synchronized <T> void put(@NonNull() String key, @Nullable() T value) Adds a key/value pair to the store.
      synchronized <T> T get(@NonNull() String key) Retrieves the value associated with a key.
      synchronized String getString(@NonNull() String key) Retrieves the string value for the give key.
      synchronized Byte getByte(@NonNull() String key) Retrieves the Byte value for the give key.
      synchronized Integer getInt(@NonNull() String key) Retrieves the Integer value for the give key.
      synchronized Double getDouble(@NonNull() String key) Retrieves the Double value for the give key.
      synchronized Short getInt16(@NonNull() String key) Retrieves the Short value for the give key.
      synchronized Long getInt64(@NonNull() String key) Retrieves the Long value for the given key.
      synchronized Float getFloat(@NonNull() String key) Retrieves the Float value for the given key.
      synchronized Array<byte> getBlob(@NonNull() String key) Retrieves the Blob (byte array) value for the given key.
      synchronized Boolean getBoolean(@NonNull() String key) Retrieves the Boolean value for the give key.
      synchronized <T extends Serializable> T getSerializable(@NonNull() String key) Retrieves the Serializable object for the give key.
      synchronized boolean hasKey(@NonNull() String key) Checks if a given key exists.
      synchronized Array<String> keys() Retrieves all the keys.
      synchronized void remove(@NonNull() String key) Removes a key-value pair from the store.
      synchronized void removeAll() Removes all entries from the store.
      synchronized void deleteStore(@NonNull() Context context) Deletes the underlying persistence store file.
      synchronized void changeEncryptionKey(@Nullable() Array<byte> newEncryptionKey) Changes the encryption key of the secure store.
      boolean storeExists() Checks if the underlying database exists.
      • Methods inherited from class java.lang.Object

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

      • SecureKeyValueStore

        SecureKeyValueStore(Context context, String storeName)
        Constructs a Secure Key Value store.
        Parameters:
        context - Android application context
        storeName - a non-empty name of the persistence store that can only contain -, _, a-z, A-Z, 0-9 and .
    • Method Detail

      • open

         synchronized void open(@Nullable() Array<byte> encryptionKey)

        Opens the key value store with the encryption key.

        Parameters:
        encryptionKey - the key to encrypt the store.
      • isOpen

         synchronized boolean isOpen()

        Checks if the store is open.

      • close

         synchronized void close()

        Closes the key value store to release system resources. Any other key value store operations are not allowed once the store is closed.

      • count

         synchronized int count()

        Returns the number of items in the key value store.

      • put

         synchronized <T> void put(@NonNull() String key, @Nullable() T value)

        Adds a key/value pair to the store.

        Parameters:
        key - String key associated with the entry
        value - the value
      • get

        @Nullable() synchronized <T> T get(@NonNull() String key)

        Retrieves the value associated with a key. Note that it is the caller's responsibility to assign the returned value to the same type(class) of variable as the value was put, otherwise, the caller will get ClassCastException.

        For example,
            final String stringKey1 = "myStringKey";
            kvStore.put(stringKey1, "myStringValue");
            ...
            Integer value = kvStore.get(stringKey1);  // Will get ClassCastException here.
        
        Parameters:
        key - the key associated with the value
      • getString

        @Nullable() synchronized String getString(@NonNull() String key)

        Retrieves the string value for the give key.

        Parameters:
        key - the key of a string value
      • getByte

        @Nullable() synchronized Byte getByte(@NonNull() String key)

        Retrieves the Byte value for the give key.

        Parameters:
        key - the key of a string value
      • getInt

        @Nullable() synchronized Integer getInt(@NonNull() String key)

        Retrieves the Integer value for the give key.

        Parameters:
        key - the key of a Integer value
      • getDouble

        @Nullable() synchronized Double getDouble(@NonNull() String key)

        Retrieves the Double value for the give key.

        Parameters:
        key - the key of a Double value
      • getInt16

        @Nullable() synchronized Short getInt16(@NonNull() String key)

        Retrieves the Short value for the give key.

        Parameters:
        key - the key of a Short value
      • getInt64

        @Nullable() synchronized Long getInt64(@NonNull() String key)

        Retrieves the Long value for the given key.

        Parameters:
        key - the key of a Long value
      • getFloat

        @Nullable() synchronized Float getFloat(@NonNull() String key)

        Retrieves the Float value for the given key.

        Parameters:
        key - the key of a Float value
      • getBlob

        @Nullable() synchronized Array<byte> getBlob(@NonNull() String key)

        Retrieves the Blob (byte array) value for the given key.

        Parameters:
        key - the key of a byte[] value
      • getBoolean

        @Nullable() synchronized Boolean getBoolean(@NonNull() String key)

        Retrieves the Boolean value for the give key.

        Parameters:
        key - the key of a Boolean value
      • getSerializable

        @Nullable() synchronized <T extends Serializable> T getSerializable(@NonNull() String key)

        Retrieves the Serializable object for the give key.

        Parameters:
        key - the key of a Serializable object
      • hasKey

         synchronized boolean hasKey(@NonNull() String key)

        Checks if a given key exists.

        Parameters:
        key - the key of a value
      • keys

        @NonNull() synchronized Array<String> keys()

        Retrieves all the keys.

      • remove

         synchronized void remove(@NonNull() String key)

        Removes a key-value pair from the store.

        Parameters:
        key - key of the entry to be removed
      • removeAll

         synchronized void removeAll()

        Removes all entries from the store.

      • deleteStore

         synchronized void deleteStore(@NonNull() Context context)

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

        Parameters:
        context - Android application context
      • changeEncryptionKey

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

        Changes the encryption key of the secure store.

        The store should have been opened with the old encryption key.

        Parameters:
        newEncryptionKey - new encryption key.
      • storeExists

        @RestrictTo(value = Scope.LIBRARY) boolean storeExists()

        Checks if the underlying database exists.