by H. Paul Robertson

H. Paul Robertson


9 June 2010

Adobe AIR allows you to create an application that uses a local SQLite database. However, one limitation of this technology used to be security-related—because all AIR applications share the same database engine, any AIR application can read any other application's database. Starting with Adobe AIR 1.5, an application can use an encrypted database. When attempting to open the database, your code must provide the database's encryption key (similar to a password). If the encryption key you specify is incorrect, the database doesn't open and an error occurs instead.

The sample application discussed in this article is intentionally simple (see Figure 1). The first time it runs, it prompts the user to enter a password. That password is used as the basis for a secure encryption key for the database. The application creates the encrypted database with the encryption key. The next time you run the application, it recognizes that you've already created the database. It prompts you for the password you used to create the database. It then recreates the encryption key using the password and attempts to open the database. If the password is correct, the database opens and the application displays a success message. Otherwise, the application displays an error message and the database is not opened.

This sample application demonstrates the following Adobe AIR features:

  • Creating an encrypted database file, using a password as the basis for the encryption key
  • Reopening an encrypted database file
  • Handling an error if the encryption key is incorrect

Note: This is a sample application provided, as is, for instructional purposes.

Understanding the code

Note: This article does not describe all of the components used in the FLA file. For more information, see the Flash CS4 ActionScript 3.0 Language and Components Reference.

Preparing to create or open an encrypted local SQL database

The init() method is called when the application finishes loading. Within this method, the code creates a SQLConnection instance name conn. (The variable conn is declared outside the method so that it is available to all the code in the application.) The code also checks whether the database file already exists, to determine whether it's creating a new database or reopening an existing one.

conn = new SQLConnection(); dbFile = File.applicationStorageDirectory.resolvePath(dbFileName); if (dbFile.exists) { createNewDB = false; // ... update the instructions and button label in the UI }

When the user clicks the button, AIR calls the openConnection() method. Regardless of whether the database exists already, the application needs to obtain the encryption key for the database which is derived from the password that the user enters. The application uses an EncryptionKeyGenerator object to create the encryption key from the user-entered password.

var keyGenerator:EncryptionKeyGenerator = new EncryptionKeyGenerator();

The first step is to check that the password meets the minimum complexity ("strength") requirements. To do this the code calls the EncryptionKeyGenerator object's validateStrongPassword() method:

var password:String = passwordInput.text; if (password == null || password.length <= 0) { statusMsg.text = "Please specify a password."; return; } if (!keyGenerator.validateStrongPassword(password)) { statusMsg.text = "[long error message left out for clarity]"; return; }

Next, the code calls the EncryptionKeyGenerator object's getEncryptionKey() method to obtain the database encryption key, passing the File object representing the database's location in the operating system and the password entered by the user:

var encryptionKey:ByteArray = keyGenerator.getEncryptionKey(password);

If the database file doesn't already exist, the EncryptionKeyGenerator object uses cryptographic techniques to create a new encryption key based on the password and returns that value. If the database does already exist, the EncryptionKeyGenerator object recreates the encryption key (using the same cryptographic techniques) and returns it.

Note: for the highest level of data privacy, your application should not store the user's password or the generated encryption key persistently (that is, it shouldn't store them beyond when the user closes the application). Instead, each time the application connects to the database the application should request the user's password and re-create the encryption key from the password. For more information, see Considerations for using encryption with a database in the guide ActionScript 3 Developer's Guide.

With the encryption key defined, the application is ready to create or open the database.

Creating or opening an encrypted database

In this example, the code uses the SQLConnection object's openAsync() method to create the encrypted database (the first time the application runs) and open a connection to the database (subsequent times when you run the application). Starting in AIR 1.5, the openAsync() method accepts an encryption key (a 16-byte ByteArray) as its sixth parameter. If an encryption key is specified, the openAsync() method creates the new database as an encrypted database, or attempts to open an encrypted database using the encryption key.

conn.addEventListener(SQLEvent.OPEN, openHandler); conn.addEventListener(SQLErrorEvent.ERROR, openError); conn.openAsync(dbFile, SQLMode.CREATE, null, false, 1024, encryptionKey);

Although this example uses the openAsync() method to open the connection in asyncronous execution mode, you can also pass an encryption key parameter to the open() method. In that case the database opens in synchronous execution mode but otherwise the operation is identical in terms of creating or opening an encrypted database.

If the openAsync() call succeeds, AIR calls the openHandler() method. This method simply cleans up the event listeners and displays the appropriate success message, depending on whether the database was created or opened:

function openHandler(event:SQLEvent):void { conn.removeEventListener(SQLEvent.OPEN, openHandler); conn.removeEventListener(SQLErrorEvent.ERROR, openError); if (createNewDB) { statusMsg.text = "The encrypted database was created successfully."; } else { statusMsg.text = "The encrypted database was opened successfully."; } }

If the openAsync() call fails, the AIR runtime calls the openError() method. This method attempts to determine whether the error was because the user is attempting to open an existing database and specified the wrong password, or for some other reason:

function openError(event:SQLErrorEvent):void { conn.removeEventListener(SQLEvent.OPEN, openHandler); conn.removeEventListener(SQLErrorEvent.ERROR, openError); if (!createNewDB && event.error.errorID == EncryptionKeyGenerator.ENCRYPTED_DB_PASSWORD_ERROR_ID) { statusMsg.text = "Incorrect password!"; } else { statusMsg.text = "Error creating or opening database."; } }

The code checks whether the createNewDB variable is true. If it is, the application is attempting to create a new database file so the problem must not be an incorrect password. Next, it checks whether the event.error.errorID property equals the constant EncryptionKeyGenerator.ENCRYPTED_DB_PASSWORD_ERROR_ID. That constant contains the error id (3138) that is dispatched when the encryption key specified in an open() or openAsync() call doesn't match the database's encryption key. (Note that the same error id can also mean that the file that was specified is not a database file at all.)


Prerequisite knowledge

General experience of building AIR applications with Flash is suggested. For more details on getting started with this Quick Start, refer to Building the Quick Start sample applications with Flash. In addition, you should also have an understanding of working with a local SQL database in AIR. For more details, see Working asynchronously with a local SQL database and Working synchronously with a local SQL database.

User level