Avg. Rating 5.0

Problem

How can I create an encrypted SQLite database for use in my AIR application?

Solution

AIR applications, as of AIR runtime 1.5 support encrypted SQLite databases. The SQLConnection class contains 'open' and 'openAsync' methods that include an optional encryptionKey parameter. The encryptionKey parameter is 16 bytes long and a ByteArray. Writing your AIR application's code to create and leverage this encryption key (using the SQLConnection class 'open' method) is shown below.

Detailed explanation

This cookbook's live example is available here. The source code is available here.

The meat and potatoes of this technique is shown in the snippet below:

import flash.data.*;
import flash.filesystem.File;

private var dbConn:SQLConnection = new SQLConnection();
private var dbStatement:SQLStatement = new SQLStatement();

private function init(): void {
  // create a seed string of your choice
  var mySeed:String = "AIR15IsAGreatProduct";

  // prepare a bytearray variable to hold the encryption key
   var myKey:ByteArray = new ByteArray();

 // create the myKey ByteArray
  var i:int = 0;
  for (var j:int=0; j<16; j++) {
    // use hexToInt function and the seed to create the key
    i = (hexToInt(mySeed.charCodeAt(j))*15) +
hexToInt(mySeed.charCodeAt(j+1));

    // use the writeByte method - Writes byte to the byte stream
    myKey.writeByte(i&0x00FF);
  }
  var dbFile:File =
File.desktopDirectory.resolvePath("Encryptedemployees.db");
  dbStatement.sqlConnection = dbConn;

  //pass the key, myKey, to the open method of the SQLConnection,
dbConn
  dbConn.open(dbFile, SQLMode.CREATE, false, 2048, myKey);
}

private function hexToInt(hex:Number):int {
    return parseInt("0x" + hex);
}

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes