Chad Upton

Encryption and Decryption with as3crypto Library

By: Chad Upton

The as3crypto library is packed with the most common encryption and decryption algorithms. In this post, I want to demonstrate how you can use the as3crypto library to encrypt and then decrypt some data that is useful in a variety of real world scenarios.

Encryption is the process used to turn plain text into unreadable information.  Decryption is the process of turning unreadable encrypted information back it into plain text.  Both operations require an encryption algorithm and key.  Anyone who has the key and algorithm can convert the encrypted information back into plain text.  This is useful when storing data or transferring data to a place where you don’t want anyone to read it.

There are half a dozen secret key encryption algorithms in as3crypto.  Some of these algorithms are better than others, and others are provided because they are common in legacy systems and may be needed for compatibility. I’m going to cover the various algorithms in a future post; for this post I’ll use AES since it is a fast and strong algorithm.

Let’s say you want to write data to an encrypted file.  Perhaps, you want to store application settings or software license info in a file, but you don’t want anyone to read it and possibly compromise your licensing system.

Follow the steps below to make an AIR app that will encrypt some data and write it to a file.

Figure 1
Figure 1
  1. Start by creating a new AIR project in Flex Builder
  2. Name the main application file Encrypt.mxml (Figure 1)
  3. Download the as3crypto library (swc file) from the project on google code
  4. Place as3crypto.swc in your AIR project’s libs folder (Figure 2)
  5. Copy the code below and replace everything in Encrypt.mxml with it
Figure 2
Figure 2
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication
xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" width="340" height="150" showStatusBar="false" verticalAlign="middle">

<mx:Script>
<![CDATA[
import com.hurlant.crypto.symmetric.AESKey;
import mx.controls.Alert;
import com.hurlant.crypto.symmetric.DESKey;
import com.hurlant.util.Hex;
import mx.charts.CategoryAxis;

private static var stream:FileStream;
private static var file:File;

private function encrypt():void
{

file = File.desktopDirectory.resolvePath("encrypted.txt");

//open a filestream to write to file
stream = new FileStream();
stream.open( file, FileMode.WRITE );

//define the encryption key
var key:ByteArray        = Hex.toArray("NewTorontoGroup");

//put plaintext into a bytearray
var plainText:ByteArray    = Hex.toArray(Hex.fromString(txtInput.text));

//set the encryption key
var aes:AESKey            = new AESKey(key);

//encrypt the text
aes.encrypt( plainText );

//write encrpted text to the file
stream.writeMultiByte( Hex.fromArray(plainText), "utf-8" );

//provide confirmation
Alert.show("Text written to file on desktop","Success");

//close the stream
stream.close();

}

]]>
</mx:Script>

<mx:TextInput id="txtInput" text="Enter text to be encrypted." />

<mx:Button label="Create File" click="encrypt()" />

</mx:WindowedApplication>

Run the Encrypt app.  Type some text into the Text Input and click the Create File button. A file called “encrypted.txt” will be written to your desktop. Open the file and look at your text in its encrypted form.  If you don’t see anything, check your encrypt application.  Try copying the code and clicking the Create File button again. Now we’ll create an app to decrypt the file.

  1. Start by creating a new MXML Application
  2. Name the file Decrypt.mxml (Figure 3)
  3. Copy the code below and replace everything in Decrypt.mxml with it
Figure 3
Figure 3
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()" showStatusBar="false">

<mx:Script>
<![CDATA[
import com.hurlant.crypto.symmetric.AESKey;
import com.hurlant.crypto.symmetric.DESKey;
import com.hurlant.util.Hex;
import mx.managers.DragManager;

private function init():void{
addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER, dragEnterHandler);
addEventListener(NativeDragEvent.NATIVE_DRAG_DROP, dragDropHandler);
}

private function dragEnterHandler( event:NativeDragEvent ):void
{

DragManager.acceptDragDrop(this);
}

private function dragDropHandler( event:NativeDragEvent ):void
{
//get the file
var file:File = File(event.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT)[0]);

//create a FileStream for the file
var fileStream:FileStream = new FileStream();

//open the file to read
fileStream.open(file, FileMode.READ);

//read the file into a string
var encryptedText:String = fileStream.readUTFBytes(fileStream.bytesAvailable);

//close the file
fileStream.close();

//define encryption key
var key:ByteArray = Hex.toArray("NewTorontoGroup");

//set key
var aes:AESKey = new AESKey(key);

//put encrypted text into ByteArray
var decryptedBytes:ByteArray = Hex.toArray( encryptedText );

//decrypt the bytearray
aes.decrypt( decryptedBytes );

//convert the decrypted bytearray to a string and display
txtDecrypted.text += decryptedBytes.toString();

}

]]>
</mx:Script>

<mx:TextArea id="txtDecrypted" text="" wordWrap="true" width="100%" height="100%" />

</mx:WindowedApplication>

Run the Decrypt app.  Minimize Flex builder and drag the “Encrypted.txt” file from your desktop and drop it on the Decrypt app.  You should see your the encrypted text displayed as decrypted plain text. This illustrated the basic mechanics required to encrypt and decrypt text in ActionScript3 using the as3crypto library.

New Toronto Group

7 Responses to “Encryption and Decryption with as3crypto Library”

  1. [...] In an earlier post I demonstrated how to take plaintext and encrypt it into an unreadable file, then decrypt it so you could read it again. This is very useful in Flash or Flex projects where you need to hide data from the user, either because it’s sensitive information such as software licenses or personal info, or because tampering with it could cause your application to function incorrectly (ex. application settings). [...]

  2. Kellyk says:

    Great article.

    The question I have is: how do you keep the secret key secret?

    It has to reside in the app binary somewhere. What is the best practice for including the secret key in the app to do these things?

    It seems like it would be not too hard to scan the binary for the key, or to identify it by somehow using a debugger.

    Also, sqlite has some encryption built-in making it easy to store encrypted data. But the same problem with the key has me up at night worrying.

    Thanks for any pointers on this.

    Kelly K
    Flex/Actionscript Developer

  3. Chad Upton says:

    Kelly,

    Great question. You’re right, it is possible for someone to decompile your swf and search for the secret key.

    Your best defense is probably going to be source code obfuscation. Basically, it’s a program that is going to go through your source code and make it virtually unreadable to someone who views it. You still retain the original source code so you can read it but the compiled version will be disguised.

    Here are a couple of obfuscators to look at. If you find something you like, please let me know. I’m planning to review some options in an upcoming post and I’d love to hear about your experience.

    SWF Encrypt
    irrFuscator

  4. Max says:

    Hi Chad,

    this tutorial is really great. I just put it in Adobe Air and all running great! Thank you very much.

    I am still quite new to Flex and one area that I have no clue is the File Stream Class.

    I want to use your code for a batch encrypter for mp3 and jpg files but I have no glue how to adjust your code to achieve this. Basically what I would like to do is to batch encrypt all .jpg files in a specific directory and save them as .enc

    It would be great if you could provide me with a few lines of code on how to achieve this.

    Thank You!
    Max

  5. Chad Upton says:

    Max,

    First, you want to create File object that points to folder for the encrypted files (use the resolvePath method)

    Then, you want to create a File object with a path of your media folder (use the resolvePath method).

    Next, use getDirectoryListing() to get an array of files in that folder.

    Then loop over that array, for each file in that array you want to do the following:

    Create a new File that will be the encrypted file.

    Read in the bytes from the unencrypted file in the array.

    Write encrypted bytes to the new file.

  6. Max says:

    Hi Chad,

    thank you so much for your hints. I am actually currently stuck at something else.

    I modified your example to encrypt mp3 files but I realized that only the first few bytes of the mp3 file are getting encrypted but not the whole file.

    I have no idea what’s the problem. Could you pls be so kind and have a look at my code below.

    Thank You
    Max

    import com.hurlant.crypto.symmetric.AESKey;
    import com.hurlant.crypto.symmetric.DESKey;
    import com.hurlant.util.Hex;

    import mx.charts.CategoryAxis;
    import mx.controls.Alert;

    private static var stream:FileStream;
    private static var stream2:FileStream;
    private static var file:File;

    private var fileToEncrypt:ByteArray;

    private function encrypt():void
    {
    file = File.documentsDirectory.resolvePath(”airenc/file1.mp3″);

    fileToEncrypt = new ByteArray;

    stream = new FileStream();
    stream.open( file, FileMode.READ );
    stream.readBytes(fileToEncrypt);
    stream.close();

    file = File.documentsDirectory.resolvePath(”airenc/file1-enc.mp3″);

    var key:ByteArray = Hex.toArray(”myEncKey”);
    var aes:AESKey = new AESKey(key);

    aes.encrypt(fileToEncrypt);

    stream2 = new FileStream();
    stream2.open( file, FileMode.WRITE );
    stream2.writeBytes(fileToEncrypt);
    stream2.close();

    }

  7. Max says:

    in the meantime I found the solution. If I replace:

    var aes:AESKey = new AESKey(key);

    with

    var aes:ICipher = Crypto.getCipher(”simple-aes-ecb”, key,Crypto.getPad(”pkcs5″));

    It encrypts the whole file.

Leave a Reply