Changing the encryption key of a database

When a database is encrypted, you can change the encryption key for the database at a later time. To change a database’s encryption key, first open a connection to the database by creating a SQLConnection instance and calling its open() or openAsync() method. Once the database is connected, call the reencrypt() method, passing the new encryption key as an argument.

Like most database operations, the reencrypt() method’s behavior varies depending on whether the database connection uses synchronous or asynchronous execution mode. If you use the open() method to connect to the database, the reencrypt() operation runs synchronously. When the operation finishes, execution continues with the next line of code:

var newKey:ByteArray = new ByteArray(); 
// ... generate the new key and store it in newKey 
conn.reencrypt(newKey);

On the other hand, if the database connection is opened using the openAsync() method, the reencrypt() operation is asynchronous. Calling reencrypt() begins the reencryption process. When the operation completes, the SQLConnection object dispatches a reencrypt event. You use an event listener to determine when the reencryption finishes:

var newKey:ByteArray = new ByteArray(); 
// ... generate the new key and store it in newKey 
     
conn.addEventListener(SQLEvent.REENCRYPT, reencryptHandler); 
     
conn.reencrypt(newKey); 
     
function reencryptHandler(event:SQLEvent):void 
{ 
    // save the fact that the key changed 
}

The reencrypt() operation runs in its own transaction. If the operation is interrupted or fails (for example, if the application is closed before the operation finishes) the transaction is rolled back. In that case, the original encryption key is still the encryption key for the database.

The reencrypt() method can’t be used to remove encryption from a database. Passing a null value or encryption key that’s not a 16-byte ByteArray to the reencrypt() method results in an error.