Class SecureKeyValueStore
-
- All Implemented Interfaces:
-
java.lang.AutoCloseable
public final class SecureKeyValueStore implements AutoCloseableThe SecureKeyValueStore is used to persist key-value pairs using an encrypted backing store. It uses
Stringas 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
Serializableinterface
EncryptionUtilto obtain the encryption key. If this is the first time store is being opened andnullis provided, an encryption key will be generated transparently and will be used for subsequent opens.
A SecureKeyValueStore hasbyte[] 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);void put(String key, T value)to add values of the supported types, and methods to retrieve different data types in an appropriate format:
You must use the appropriate method to retrieve the data from the key-value store by passing a String key: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 can use keys to retrieve the keys of existing entries: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 remove one or all existing entries in the store: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 change the encryption of the underlying persistence store when the store is in open state.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); }
When you finish executing key-value store operations, close the SecureKeyValueStore to relinquishes any resources it has acquired during its operations:store.changeEncryptionKey(newEncryptionKey);store.close();
-
-
Constructor Summary
Constructors Constructor Description SecureKeyValueStore(Context context, String storeName)Constructs a Secure Key Value store.
-
Method Summary
Modifier and Type Method Description synchronized voidopen(@Nullable() Array<byte> encryptionKey)Opens the key value store with the encryption key. synchronized booleanisOpen()Checks if the store is open. synchronized voidclose()Closes the key value store to release system resources. synchronized intcount()Returns the number of items in the key value store. synchronized <T> voidput(@NonNull() String key, @Nullable() T value)Adds a key/value pair to the store. synchronized <T> Tget(@NonNull() String key)Retrieves the value associated with a key. synchronized StringgetString(@NonNull() String key)Retrieves the string value for the give key. synchronized BytegetByte(@NonNull() String key)Retrieves the Bytevalue for the give key.synchronized IntegergetInt(@NonNull() String key)Retrieves the Integervalue for the give key.synchronized DoublegetDouble(@NonNull() String key)Retrieves the Doublevalue for the give key.synchronized ShortgetInt16(@NonNull() String key)Retrieves the Shortvalue for the give key.synchronized LonggetInt64(@NonNull() String key)Retrieves the Longvalue for the given key.synchronized FloatgetFloat(@NonNull() String key)Retrieves the Floatvalue for the given key.synchronized Array<byte>getBlob(@NonNull() String key)Retrieves the Blob (byte array) value for the given key. synchronized BooleangetBoolean(@NonNull() String key)Retrieves the Booleanvalue for the give key.synchronized <T extends Serializable> TgetSerializable(@NonNull() String key)Retrieves the Serializable object for the give key. synchronized booleanhasKey(@NonNull() String key)Checks if a given key exists. synchronized Array<String>keys()Retrieves all the keys. synchronized voidremove(@NonNull() String key)Removes a key-value pair from the store. synchronized voidremoveAll()Removes all entries from the store. synchronized voiddeleteStore(@NonNull() Context context)Deletes the underlying persistence store file. synchronized voidchangeEncryptionKey(@Nullable() Array<byte> newEncryptionKey)Changes the encryption key of the secure store. booleanstoreExists()Checks if the underlying database exists. -
-
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.
- Returns:
Trueif the store is open,falseotherwise.
-
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.
- Returns:
The number of key-value pairs or 0 if there are no key-value pairs.
-
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 entryvalue- 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- Returns:
The value associated with the
key.
-
getString
@Nullable() synchronized String getString(@NonNull() String key)
Retrieves the string value for the give key.
- Parameters:
key- the key of a string value- Returns:
A
Stringvalue ornullif the key is not found.
-
getByte
@Nullable() synchronized Byte getByte(@NonNull() String key)
Retrieves the
Bytevalue for the give key.- Parameters:
key- the key of a string value- Returns:
A
Bytevalue ornullif the key is not found.
-
getInt
@Nullable() synchronized Integer getInt(@NonNull() String key)
Retrieves the
Integervalue for the give key.- Parameters:
key- the key of aIntegervalue- Returns:
An
Integervalue ornullif the key is not found.
-
getDouble
@Nullable() synchronized Double getDouble(@NonNull() String key)
Retrieves the
Doublevalue for the give key.- Parameters:
key- the key of aDoublevalue- Returns:
A
Doublevalue ornullif the key is not found.
-
getInt16
@Nullable() synchronized Short getInt16(@NonNull() String key)
Retrieves the
Shortvalue for the give key.- Parameters:
key- the key of aShortvalue- Returns:
A
Shortvalue ornullif the key is not found.
-
getInt64
@Nullable() synchronized Long getInt64(@NonNull() String key)
Retrieves the
Longvalue for the given key.- Parameters:
key- the key of aLongvalue- Returns:
A
Longvalue ornullif the key is not found.
-
getFloat
@Nullable() synchronized Float getFloat(@NonNull() String key)
Retrieves the
Floatvalue for the given key.- Parameters:
key- the key of aFloatvalue- Returns:
A
Floatvalue ornullif the key is not found.
-
getBlob
@Nullable() synchronized Array<byte> getBlob(@NonNull() String key)
Retrieves the Blob (byte array) value for the given key.
- Parameters:
key- the key of abyte[]value- Returns:
A
byte[]value ornullif the key is not found.
-
getBoolean
@Nullable() synchronized Boolean getBoolean(@NonNull() String key)
Retrieves the
Booleanvalue for the give key.- Parameters:
key- the key of aBooleanvalue- Returns:
A
Booleanvalue ornullif the key is not found.
-
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- Returns:
A Serializable object or
nullif the key is not found.
-
hasKey
synchronized boolean hasKey(@NonNull() String key)
Checks if a given key exists.
- Parameters:
key- the key of a value- Returns:
Trueif the key exists,falseotherwise.
-
keys
@NonNull() synchronized Array<String> keys()
Retrieves all the keys.
- Returns:
An array of existing keys or an empty array.
-
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.
- Returns:
Trueif the database file exists,falseotherwise.
-
-
-
-