EncryptedLocalStore File variable with getter/setter

The EncryptedLocalStore (ELS) is a decent place to persist user specific settings like for instance a username and a password. As the name already says the ELS content is stored encrypted using the Keychain of OS X and DPAPI on Windows with AES-CBC 128-bit encryption.

The code to store a File variable in ELS using a getter and setter of a class:

package com.soenkerohde.example.model
{
	import flash.data.EncryptedLocalStore;
	import flash.filesystem.File;
	import flash.utils.ByteArray;
 
	public class AppModel
	{
 
		protected static const WORK_DIR:String = "workDir";
 
		private var _workDir:File;
 
		/**
		 * 
		 * @return workDir File default documents directory
		 * 
		 */		
		[Bindable]
		public function get workDir():File
		{
			if(_workDir == null)
			{
				var ba:ByteArray = EncryptedLocalStore.getItem(WORK_DIR);
				var path:String = ba != null ? ba.readUTFBytes(ba.length) as String : File.documentsDirectory.nativePath;
				_workDir = new File(path);
			}
			return _workDir;
		}
 
		/**
		 * 
		 * @param dir directory File.
		 * value is stored in ELS
		 * set with null to remove ELS value
		 * 
		 */		
		public function set workDir(dir:File):void
		{
			_workDir = dir;
			if(dir != null)
			{
				var ba:ByteArray = new ByteArray();
				ba.writeUTFBytes(dir.nativePath);
				EncryptedLocalStore.setItem(WORK_DIR, ba);
			}
			else
			{
				EncryptedLocalStore.removeItem(WORK_DIR);
			}
		}
 
		public function AppModel()
		{
		}
 
	}
}

As you see the workDir is also bindable so you can use it as the source of for instance an AIR FileSystemTree directory.

To persist typed objects you have to add the RemoteClass metadata to the corresponding class. Variables which should not be persisted can be marked transient (works the same like with RemoteObject):

package com.soenkerohde.example.domain
{
 
	[RemoteClass(type="com.soenkerohde.example.domain.Contact")]
	public class Contact
	{
		public var name:String;
		public var email:String;
 
		[Transient]
		public var someTempVar:String;
		// ...

There are many options to store data on the client side. You could also use a SharedObject, a SQLite database or also the filesystem where you could store for instance a XML file on the users harddrive or whatever you have in mind.
Since the ELS API is synchronous you should avoid large amount of data to not decrease the performance of your software.

7 comments to EncryptedLocalStore File variable with getter/setter