Have you ever wanted to store a users password, you know, that little checkbox that says ‘Save Password’ on any login form. Or maybe you just want to persist a session token or other information. You could use the Local Shared Objects or even the File API, but that isn’t very secure. How do you store sensitive information that your AIR application needs to persist?
Luckily, there is an often overlooked API for just this use case. It is called the EncryptedLocalStore and is actually quite simple to use. The EncryptedLocalStore API persists data to the local system using a name-value pair scheme that is specific to each application. The name is a simple string, and the data is a ByteArray. The data is stored using both the application ID and the user information from the local system, so other AIR applications and other users cannot access the data. This API is actually hooking into the Keychain functionality on Mac and DPAPI on Windows. The data is encrypted using AES-CBC 128-bit encryption. So the main point to take away is that the data is very secure and other AIR apps or users will not be able to easily access it.
So, how do you actually use the API? Well, lets assume that we have a session ID that is a string and we want to persist in the EncryptedLocalStore. Lets also assume that the session ID is stored in a variable called ‘sessionId’. One thing to keep note of is that the data must be stored as a ByteArray, so we first need to create a ByteArray instance and add the string value to it. The code might look something like this:
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes( sessionId );
EncryptedLocalStore.setItem( “sessionId”, bytes );
To retrieve the data, you simple retrieve the ByteArray using the getItem API, and then read your UTF string value out of that ByteArray:
var sessionIdBytes:ByteArray = EncryptedLocalStore.getItem(“sessionId”);
var sessionId:String = sessionIdBytes.readUTFBytes( sessionIdBytes.length);
To remove an item from the store, you simply call the removeItem API:
There are a few things to note when using the EncryptedLocalStore API. First, the API is syncronous and is geared towards small amounts of data. While there is no practical limit, any ByteArrays larger than 10MB might cause performance issues. Second, when debugging your application using ADL, we are actually using a different store than what is being used for installed applications. And last, when uninstalling an AIR application, the data in the EncryptedLocalStore is NOT deleted.
One last note as well, this API is available to both Ajax and Flash based AIR applications, like all ActionScript APIs.