public final class

SecureKeyValueStore

extends Object
java.lang.Object
   ↳ com.sap.cloud.mobile.foundation.securestore.SecureKeyValueStore

Class Overview

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

Creating and Opening

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:

Put

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

Get

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

Getting Keys

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

Removing Entry/Entries

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

Changing Encryption Key

You can change the encryption of the underlying persistence store when the store is in open state.
store.changeEncryptionKey(newEncryptionKey);
 

Closing Key-Value Store

When you finish executing key-value store operations, close() the SecureKeyValueStore to relinquishes any resources it has acquired during its operations:
store.close();
 

Summary

Public Constructors
SecureKeyValueStore(Context context, String storeName)
Constructs a Secure Key Value store.
Public Methods
synchronized void changeEncryptionKey(byte[] newEncryptionKey)
Changes the encryption key of the secure store.
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 void deleteStore(Context context)
Deletes the underlying persistence store file.
synchronized <T> T get(String key)
Retrieves the value associated with a key.
synchronized byte[] getBlob(String key)
Retrieves the Blob (byte array) value for the given key.
synchronized Boolean getBoolean(String key)
Retrieves the Boolean value for the give key.
synchronized Byte getByte(String key)
Retrieves the Byte value for the give key.
synchronized Double getDouble(String key)
Retrieves the Double value for the give key.
synchronized Float getFloat(String key)
Retrieves the Float value for the given key.
synchronized Integer getInt(String key)
Retrieves the Integer value for the give key.
synchronized Short getInt16(String key)
Retrieves the Short value for the give key.
synchronized Long getInt64(String key)
Retrieves the Long value for the given key.
synchronized <T extends Serializable> T getSerializable(String key)
Retrieves the Serializable object for the give key.
synchronized String getString(String key)
Retrieves the string value for the give key.
synchronized boolean hasKey(String key)
Checks if a given key exists.
synchronized boolean isOpen()
Checks if the store is open.
synchronized String[] keys()
Retrieves all the keys.
synchronized void open(byte[] encryptionKey)
Opens the key value store with the encryption key.
synchronized <T> void put(String key, T value)
Adds a key/value pair to the store.
synchronized void remove(String key)
Removes a key-value pair from the store.
synchronized void removeAll()
Removes all entries from the store.
[Expand]
Inherited Methods
From class java.lang.Object

Public Constructors

public 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 .
Throws
BackingStoreException if failed to create the underlying persistence store.

Public Methods

public synchronized void changeEncryptionKey (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. It is recommended to use EncryptionUtil to obtain the new encryption key. If null is provided, an encryption key will be generated transparently and will be used for subsequent opens.
Throws
FileClosedException if the store has been closed.
EncryptionError

public 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.

public synchronized int count ()

Returns the number of items in the key value store.

Returns
  • The number of key-value pairs or 0 if there are no key-value pairs.
Throws
FileClosedException if the persistence store has been closed.

public synchronized void deleteStore (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

public synchronized T get (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(String, Object), 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
Returns
  • The value associated with the key.

public synchronized byte[] getBlob (String key)

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

Parameters
key the key of a byte[] value
Returns
  • A byte[] value or null if the key is not found.
Throws
FileClosedException if the store has been closed.

public synchronized Boolean getBoolean (String key)

Retrieves the Boolean value for the give key.

Parameters
key the key of a Boolean value
Returns
  • A Boolean value or null if the key is not found.
Throws
FileClosedException if the store has been closed.

public synchronized Byte getByte (String key)

Retrieves the Byte value for the give key.

Parameters
key the key of a string value
Returns
  • A Byte value or null if the key is not found.
Throws
FileClosedException if the store has been closed.

public synchronized Double getDouble (String key)

Retrieves the Double value for the give key.

Parameters
key the key of a Double value
Returns
  • A Double value or null if the key is not found.
Throws
FileClosedException if the store has been closed.

public synchronized Float getFloat (String key)

Retrieves the Float value for the given key.

Parameters
key the key of a Float value
Returns
  • A Float value or null if the key is not found.
Throws
FileClosedException if the store has been closed.

public synchronized Integer getInt (String key)

Retrieves the Integer value for the give key.

Parameters
key the key of a Integer value
Returns
  • An Integer value or null if the key is not found.
Throws
FileClosedException if the store has been closed.

public synchronized Short getInt16 (String key)

Retrieves the Short value for the give key.

Parameters
key the key of a Short value
Returns
  • A Short value or null if the key is not found.
Throws
FileClosedException if the store has been closed.

public synchronized Long getInt64 (String key)

Retrieves the Long value for the given key.

Parameters
key the key of a Long value
Returns
  • A Long value or null if the key is not found.
Throws
FileClosedException if the store has been closed.

public synchronized T getSerializable (String key)

Retrieves the Serializable object for the give key.

Parameters
key the key of a Serializable object
Returns
Throws
FileClosedException if the store has been closed.
TypeConversionException if the object cannot be de-serialized.
ClassCastException if the class of the returned object is different from the object's class during put(String, Object).

public synchronized String getString (String key)

Retrieves the string value for the give key.

Parameters
key the key of a string value
Returns
  • A String value or null if the key is not found.
Throws
FileClosedException if the store has been closed.

public synchronized boolean hasKey (String key)

Checks if a given key exists.

Parameters
key the key of a value
Returns
  • True if the key exists, false otherwise.
Throws
FileClosedException if the store has been closed.

public synchronized boolean isOpen ()

Checks if the store is open.

Returns
  • True if the store is open, false otherwise.

public synchronized String[] keys ()

Retrieves all the keys.

Returns
  • An array of existing keys or an empty array.
Throws
FileClosedException if the store has been closed.

public synchronized void open (byte[] encryptionKey)

Opens the key value store with the encryption key.

Parameters
encryptionKey the key to encrypt the store. 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.
Throws
OpenFailureException if the encryption key is incorrect or failed to generate the encryption key.

public synchronized void put (String key, T value)

Adds a key/value pair to the store.

Parameters
key String key associated with the entry
value the value
Throws
TypeConversionException if the T (class) of value is not supported.

public synchronized void remove (String key)

Removes a key-value pair from the store.

Parameters
key key of the entry to be removed
Throws
FileClosedException if the store has been closed.
BackingStoreException if the query fails.

public synchronized void removeAll ()

Removes all entries from the store.

Throws
FileClosedException if the store has been closed.
BackingStoreException if the query fails.