- 26 Dec 2024
- 1 Minute à lire
- SombreLumière
- PDF
Example code, illustrating the usage of the Secure Local Storage API
- Mis à jour le 26 Dec 2024
- 1 Minute à lire
- SombreLumière
- PDF
The example shows a class SLSExample which provides some API tomanage the Secure Local Storage data for a single fixed key.
package com.example.sls; import java.io.IOException; import java.io.UnsupportedEncodingException; import no.promon.shield.storage.local.SecureLocalStorage; public class SLSExample { private static final String CHARSET_UTF8 = "UTF-8"; private static final String KEY = "Data tag"; private final SecureLocalStorage storage; SLSExample() { storage = SecureLocalStorage.getInstance(); } ... }
The constructor calls the static function SecureLocalStorage.getInstance() to get access to the SecureLocalStorage singleton instance.
Function storing data in the Secure Local Storage.
... void saveData() { try { String data = "Sensitive data to be stored."; storage.put(KEY, data.getBytes(CHARSET_UTF8)); } catch (UnsupportedEncodingException e) { throw new RuntimeException( "Internal Error: Android is expected to support UTF-8 encoding", e); } catch (IOException e) { throw new RuntimeException("Could not save data.", e); } } ...
The function calls SecureLocalStorage.put() to store data in the Secure Local Storage. put() stores a value as a byte[], so our example converts the String data to UTF-8 bytes before storing it.
Function retrieving data from the Secure Local Storage.
... void retrieveData() { String data; try { byte[] dataRetrieved = storage.get(KEY); if (dataRetrieved == null) { // error handling return; } data = new String(dataRetrieved, CHARSET_UTF8); } catch (UnsupportedEncodingException e) { throw new RuntimeException( "Internal Error: Android is expected to support UTF-8 encoding", e); } catch (IOException e) { throw new RuntimeException("Could not retrieve data.", e); } // The storage had a value for the key, access it through data... } ...
The function calls SecureLocalStorage.get() to read the stored data from the Secure Local Storage. get() returns the value as a byte[]. Since we know that saveData() stored a UTF-8 encoded string, we can create a new String from the UTF-8 bytes.
The method SecureLocalStorage.get() returns null if there is no value for the requested key or if the Secure Local Storage could not decrypt the data because of data corruption. For example if an external party modified the content of the Secure Local Storage file. The API does not distinguish these cases to avoid key enumeration during Information Disclosure types of attack.
Function removing data from the Secure Local Storage.
... void removeData() { try { storage.remove(KEY); } catch (IOException e) { throw new RuntimeException("Could not remove data.", e); } } }
The function calls SecureLocalStorage.remove() to delete stored data.