Use Worklight to encrypt the data stored in window.localStorage

In the Reading data stored in localStroage by Android Device or Google Chrome Browser entry i talked about how easy it is to read data stored by web application in the window.localStorage object. WOrklight provides alternative which is to use a Encrypted cache that still uses window.localStorage object to store the data but encrypts the actual data to make it harder for someone else to read that data, even if they get access to your mobile or desktop. I wanted to try this feature out so i built this simple application which lets me store and read data from encrypted cache
First i did build a simple HTML file like this

<!DOCTYPE html>    
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, 
    initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" />
    <title>HelloEncryptedCache</title>
    <link rel="shortcut icon" href="images/favicon.png" />
    <link rel="apple-touch-icon" href="images/apple-touch-icon.png" />
    <link rel="stylesheet" href="css/reset.css" />
    <link rel="stylesheet" href="css/HelloEncryptedCache.css" />
  </head>
  <body onload="WL.Client.init({})" id="content" style="display: none">
    <h1>Encrypted Cache</h1>
    <table>
      <tr>
        <td>Encryption Key</td>
        <td><input type="text" name='encryptionKey' id="encryptionKey" /></td>
      </tr>
      <tr>
        <td><button id="openCache">Open Cache</button></td>
        <td><button id="closeCache">Close Cache</button></td>
      </tr>
      <tr>
        <td><button id="destroyCache">Destroy Cache</button></td>
      </tr>
      <tr>
        <td>Key</td>
        <td><input type="text" name='key' id="key" /></td>
      </tr>
      <tr>
        <td>value</td>
        <td><input type="text" name='value' id="value" /></td>
      </tr>
      <tr>
        <td><button id="encryptKey">Encrypt Key/Value</button></td>
        <td><button id="decryptKey">Decrypt Key</button></td>
      </tr>
      <tr>
        <td><button id="removeKey">Remove key</button></td>
      </tr>
    </table>
    <script src="js/HelloEncryptedCache.js"></script>
    <script src="js/messages.js"></script>
    <script src="js/auth.js"></script>
  </body>
</html>
This is how my JavaScript on the page looks like

window.$ = WLJQ;

function wlCommonInit(){
  $("#openCache").click(function(){
    console.log('The openCache button is clicked ' +$("#encryptionKey").val());
    WL.EncryptedCache.open($("#encryptionKey").val(), true, function(){
      console.log('The cache key opened successfully');
    },onOpenError);
  });
  $("#closeCache").click(function(){
    console.log('The closeCache button is clicked');
    WL.EncryptedCache.close(function(){
      console.log('The cache is closed successfully');
    });
  });
  $("#destroyCache").click(function(){
    console.log('The destroyCache button is clicked');
    WL.EncryptedCache.destroy(function(){
      console.log('Successfully destroyed the encrypted cache');
    });
  });
  $("#encryptKey").click(function(){
    console.log('The encryptKey button is clicked');
    WL.EncryptedCache.write($("#key").val(), $("#value").val(), function() {
      console.log('The entry written successfully');
    }, function(status){
      console.log('There was error in encryptingKey ' + status);
      switch(status){
      case WL.EncryptedCache.ERROR_KEY_CREATION_IN_PROGRESS:
        console.log('Error in key creation process');
        break;
      case WL.EncryptedCache.ERROR_LOCAL_STORAGE_NOT_SUPPORTED:
        console.log('Local storage is not supported');
        break;
      case WL.EncryptedCache.ERROR_NO_EOC:
        console.log('No EOC');
        break;
      case WL.EncryptedCache.ERROR_COULD_NOT_GENERATE_KEY:
        console.log('Could not generate key');
        break;
      case WL.EncryptedCache.ERROR_CREDENTIALS_MISMATCH:
        console.log('Credentials mismatch');
        break;
      }
    }); 
  });
  $("#decryptKey").click(function(){
    console.log('The decryptKey button is clicked');
    WL.EncryptedCache.read($('#key').val(), function(value) {
      console.log('Value from the encrypted cache is ' + value);
      alert('Encrypted value for the key -> ' + value);
    }, function(status){
      console.log('There was error in encryptingKey ' + status);
      switch(status){
      case WL.EncryptedCache.ERROR_KEY_CREATION_IN_PROGRESS:
        console.log('Error in key creation process');
        break;
      case WL.EncryptedCache.ERROR_LOCAL_STORAGE_NOT_SUPPORTED:
        console.log('Local storage is not supported');
        break;
      case WL.EncryptedCache.ERROR_NO_EOC:
        console.log('No EOC');
        break;
      case WL.EncryptedCache.ERROR_COULD_NOT_GENERATE_KEY:
        console.log('Could not generate key');
        break;
      case WL.EncryptedCache.ERROR_CREDENTIALS_MISMATCH:
        console.log('Credentials mismatch');
        break;
      }
    });
  });
  $("#removeKey").click(function(){
    console.log('The removeKey button is clicked');
    WL.EncryptedCache.remove($('#key').val(), function(){
      console.log('The encrypted key removed successfully ->' + $('#key').val() );
    })
  });
}
function onOpenError(status) {
  console.log("Inside onOpenError " + status);
  switch (status) {
  case WL.EncryptedCache.ERROR_KEY_CREATION_IN_PROGRESS:
    console.log("Error key creation in progress");
    break;
  case WL.EncryptedCache.ERROR_LOCAL_STORAGE_NOT_SUPPORTED:
    console.log("Error local storage not supported");
    break;
  case WL.EncryptedCache.ERROR_CREDENTIALS_MISMATCH:
    console.log("Error credentials mismatch");
    break;
  case WL.EncryptedCache.ERROR_SECURE_RANDOM_GENERATOR_UNAVAILABLE:
    console.log("Error secure random generator unavailable");
    break;
  case WL.EncryptedCache.ERROR_NO_EOC:
    console.log("Error no eoc");
    break;
  }
}
The JavaScript has one event handler for each of the button and when you click on the button it makes use of the WL.EncryptedCache API to read/write cache entries. While working with encrypted cache first you have to open the cache before you can write any entry and once your done writing cache entries you will have to close the cache. I noticed one strange thing is if i dont attach error handling functions then my code works in normal browser but it throws undefined error in ANdroid emulator. It seems that the Worklight API makes use of some native device functionality to get encrypted cache working. One thing i noticed is accessing encrypted cache (specially opening it is really slow, so you should use it only if you really need to encrypt the data) After storing data using the Encrypted Cache API i tried to access the file_0.localstorage file from the device but i could not download it due to some file access level restrictions that android is putting on it.
Also in the local browser i can not read the values stored in the encryptedCache

Reading data stored in localStroage by Android Device or Google Chrome Browser

While working on my Using localStorage/sessionStorage in PhoneGap application example i was trying to debug a issue on the Android device where the data was not getting stored properly (Due to my programming mistake) and i wanted to figure out what data is actually getting stored so i used these steps.
  1. First i used the DDMS view in Eclipse to get access to the local file system on Andorid. All the data for an application is stored in andorid in data/data/<apppackage> folder, In my case application package name is com.HelloLocalStorage
    Whatever you store in window.localStorage object is actually stored in the data/data/<apppackage>/app_database/file_0.localstorage file, first download it to your computer. This file is actually SQLLite database, so if you open it in normal notepad you wont be able to read it. When you store data in localStroage object in the Google chrome it gets stored in C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default\Local Storage directory.
  2. If you want to open SQLLite database you will have to use one of the admin tools, i used the MikeTS SQLLite Management tool to open the file_0.localstorage file and it seems that Google Chrome stores the localStorage data in ItemTable, that table has 2 columns one is key and other is value, when i queried the ItemTable i could see the data stored in local preferences like this

Using localStorage/sessionStorage in PhoneGap application

The HTML 5 specification introduced 2 objects that can be used for storing data in key-value format on the client side, i wanted to try this feature out so i did create this simple Todo list web page that can be used to create a TO DO list. This is how my Todo list application looks like
This is the HTML page that i created for working with

 <!DOCTYPE html>
<html manifest="storage.appcache">
  <head>
    <title>Offline Application Example</title>
    <script type="text/javascript" charset="utf-8" 
 src="jquery.js"></script>
    <script type="text/javascript" charset="utf-8">
    var storage = window.localStorage;
    $(document).ready(function(){
      console.log('Inside document.ready');
      initTodoList();
      $("#clearStorage").click(function(){
        console.log('Entering clearstorage');
        storage.clear();
        $('li').remove();
        console.log('Exiting clearstorage');
      });
    });
    function remove_item(key){
      console.log('Entering remove_item');
      storage.removeItem(key);
      console.log('Find and remove element with id = ' + key)
      $('#'+key).remove();
      console.log('Exiting remove_item');
    }
    function add_item() {
      console.log('Entering add_item');
      var d = new Date();
      var key = d.getTime();
      var value = $('#new_item').val();
      storage.setItem(key,value);
      createToDoListItem(key,value);
      $("#new_item").val('');
      console.log('Exiting add_item');
    }
    function initTodoList(){
      console.log("Entering initTodoList " + storage.length);
      for(var i = 0; i < storage.length; i++){
        var key = storage.key(i);
        var value = storage.getItem(key);
        createToDoListItem(key,value);
      }
    }  
    function createToDoListItem(key, value){
      var html = '<li  data-key="'+key+'" id="'+key+'">'
      +value+'<button onclick="javascript:remove_item(\''+ key+ '\')" 
   >Delete</button></li>';
      console.log('Appending html ' + html)
      $("#todo_list").append(html);
    }
    </script>
  </head>
  <body>
    <input type="text" id="new_item">
  <button onclick="add_item()">
  Add
  </button>
  <ul id="todo_list">
  </ul>
    <br/>
  <button id="clearStorage">Clear storage</button>
  </body>
</html>
You can use either localStorage, in which case the data is storage across browser restarts or you can use the sessionStorage in which case you will loose the TODO list once the browser is closed. All you have to do is change the value of var storage = either window.localStorage or window.sessionStorage Chrome developer tools allows us to look at the data stored in the localStorage as well as remove that data.