Archive for the ‘AIR’ Category

oliverm

Flex Camp Roundup

Friday, June 25th, 2010

June 25, 2010

On June 10th, 2010 we hosted the third Toronto Flex Camp. Ed Van Beilen and myself are co-managers of the Toronto Flex User Group, which is in its fourth year and sporting over 1000 members in the GTA.

Unlike previous camps, this year’s event included hands-on sessions and spanned a full afternoon and evening. We were fortunate enough to have two Adobe representatives (Lee Brimelow and Renaun Erickson) lead several sessions, including the keynote. We also had a few people from our local Flex User Group step up and present: Jason Broughton, Andrew Rybak, Clement Wong and Derek Santos.

In presenting this event, we learned a few lessons and gathered some interesting statistics that I’d like to share.

Significantly, this is the first time we’ve charged for entry into a Toronto Flex Camp. To our delight, we did not receive a single complaint about the $25 CAD entry fee. By charging this nominal fee, we were able to increase the quality of the venues and catered fare.

Financially, we did a bit better than break even. This small surplus will be used to offset the costs of future regular meetings, which New Toronto Group has traditionally absorbed.

The Numbers

Of the 120 people who registered on the site, 112 completed the payment process.

Of the 112 paid registrants, 83 showed up, and we had 2 additional registrations at the door (despite our pleas that people register in advance) for a total of 85 attendees (76%).

Out of the 85 attendees, 61% filled out the survey and qualified to be in the prize draw.

Speaking of the survey, here’s how you rated the event:

  • Quality of the presentations: 82%

  • Usefulness of the event: 76%

  • Overall quality of the event: 83%

  • Would attend another Flex Camp: 94%

Looks like we did fairly well with the new format. That last number is probably the most important for us as we look at the feasibility of future Flex Camps.

Your Feedback

Everyone seemed pleased with the venue and location, but we definitely needed more signage to direct people to the various venues. Thanks again to Brian Lesser and the folks at Ryerson for their invaluable help.

You also gave us some valuable feedback about the sessions themselves.

Foremost in the comments we received was to have more sessions, especially hands-on. Of course, the challenge is to find enough session leaders, so we may be pushing the local Flex community to help out more in the future.

Many of you also asked that the sessions be shorter in duration, perhaps limited to an hour. No argument here; just a matter of getting enough speakers to fill all those hours;)

We seem to have struck a good balance between introductory and advanced topics. Like in politics, you know you’ve done the right thing if an equal number of people on both sides complain. In our case, we had just as many people comment that they wanted more fundamental topics as those that wanted more advanced ones.

Looking Forward

One surprise we had in the Management Session (led by Andrew and me) was the intense interest in mobile. In fact, about three slides into our RIA presentation we decided to completely change gears and focus the discussion on the upcoming Flash/mobile releases. No doubt that there will be more mobile content in future meetings.

Overall, Flex Camp 3 Toronto was a great success and we look forward to doing another one in the future. Please check the Toronto Flex User Group website for Fall meeting announcements and job postings at http://www.torontoflex.org. And if you’d like to lead a future session or have an idea for a meeting topic, please contact Ed or me via the link on the site.

Finally, thanks to all who attended and gave us such encouraging feedback.

See you in the Fall!

June 25, 2010

Flex Camp Roundup

On June 10th, 2010 we hosted the third Toronto Flex Camp. Ed Van Beilen and myself are co-managers of the Toronto Flex User Group, which is in its fourth year and sporting over 1000 members in the GTA.

Unlike previous camps, this year’s event included hands-on sessions and spanned a full afternoon and evening. We were fortunate enough to have two Adobe representatives (Lee Brimelow and Renaun Erickson) lead several sessions, including the keynote. We also had a few people from our local Flex User Group step up and present: Jason Broughton, Andrew Rybak, Clement Wong and Derek Santos.

In presenting this event, we learned a few lessons and gathered some interesting statistics that I’d like to share.

Significantly, this is the first time we’ve charged for entry into a Toronto Flex Camp. To our delight, we did not receive a single complaint about the $25 CAD entry fee. By charging this nominal fee, we were able to increase the quality of the venues and catered fare.

Financially, we did a bit better than break even. This small surplus will be used to offset the costs of future regular meetings, which New Toronto Group has traditionally absorbed.

The Numbers

Of the 120 people who registered on the site, 112 completed the payment process.

Of the 112 paid registrants, 83 showed up, and we had 2 additional registrations at the door (despite our pleas that people register in advance) for a total of 85 attendees (76%).

Out of the 85 attendees, 61% filled out the survey and qualified to be in the prize draw.

Speaking of the survey, here’s how you rated the event:

  • Quality of the presentations: 82%

  • Usefulness of the event: 76%

  • Overall quality of the event: 83%

  • Would attend another Flex Camp: 94%

Looks like we did fairly well with the new format. That last number is probably the most important for us as we look at the feasibility of future Flex Camps.

Your Feedback

Everyone seemed pleased with the venue and location, but we definitely needed more signage to direct people to the various venues. Thanks again to Brian Lesser and the folks at Ryerson for their invaluable help.

You also gave us some valuable feedback about the sessions themselves.

Foremost in the comments we received was to have more sessions, especially hands-on. Of course, the challenge is to find enough session leaders, so we may be pushing the local Flex community to help out more in the future.

Many of you also asked that the sessions be shorter in duration, perhaps limited to an hour. No argument here; just a matter of getting enough speakers to fill all those hours;)

We seem to have struck a good balance between introductory and advanced topics. Like in politics, you know you’ve done the right thing if an equal number of people on both sides complain. In our case, we had just as many people comment that they wanted more fundamental topics as those that wanted more advanced ones.

Looking Forward

One surprise we had in the Management Session (led by Andrew and me) was the intense interest in mobile. In fact, about three slides into our RIA presentation we decided to completely change gears and focus the discussion on the upcoming Flash/mobile releases. No doubt that there will be more mobile content in future meetings.

Overall, Flex Camp 3 Toronto was a great success and we look forward to doing another one in the future. Please check the Toronto Flex User Group website for Fall meeting announcements and job postings at http://www.torontoflex.org. And if you’d like to lead a future session or have an idea for a meeting topic, please contact Ed or me via the link on the site.

Finally, thanks to all who attended and gave us such encouraging feedback.

See you in the Fall!

alaint

Open Source Media Framework (OSMF) Helloworld example in Flex 4

Wednesday, April 21st, 2010

By Alain Thibodeau – Consultant

If you have ever built a video player from scratch you know the hard work that is involved. The Open Source Media Framework helps developers to create video players using best practices and avoid solving the same problems over and over, saving time and money. You can learn more about OSMF at this website.

OSMF ships with Flex 4

OSMF comes with Flex 4.  This is great, but the included version is an earlier version of OSMF. At this writing, the version of OSMF is v0.93 sprint 10. This version includes several changes since the version that ships with Flex 4. You’ll need to remove the osmf.swc from the Flex 4 SDK and add the proper osmf.swc in your project libs folder. Download the latest OSMF files here.

Making the example work in Flex 4:

1. Make the HelloWorld.as extend UIComponent instead of Sprite.
2. Create a project MXML file and create an instance of the HelloWorld class in either AS3 or in MXML. I show both ways below, but I’ve commented out the MXML way of doing it.

Example code: main.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:Application
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:local="*"
    minWidth="955"
    minHeight="600"
    creationComplete="init(event)"
    >
    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            public var helloWorld:HelloWorld
           
            protected function init( event:FlexEvent ):void {
                helloWorld = new HelloWorld();
                addElement( helloWorld );
            }
        ]]>
    </fx:Script>
    <!--<local:HelloWorld />-->
</s:Application>

Example code: HelloWorld.as

/*****************************************************
 *
 *  Copyright 2009 Adobe Systems Incorporated.  All Rights Reserved.
 *
 *****************************************************
 *  The contents of this file are subject to the Mozilla Public License
 *  Version 1.1 (the "License"); you may not use this file except in
 *  compliance with the License. You may obtain a copy of the License at
 *  http://www.mozilla.org/MPL/
 *
 *  Software distributed under the License is distributed on an "AS IS"
 *  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 *  License for the specific language governing rights and limitations
 *  under the License.
 *
 *
 *  The Initial Developer of the Original Code is Adobe Systems Incorporated.
 *  Portions created by Adobe Systems Incorporated are Copyright (C) 2009 Adobe Systems
 *  Incorporated. All Rights Reserved.
 *
 *****************************************************/
package {
    import flash.display.Sprite;
   
    import mx.core.UIComponent;
   
    import org.osmf.containers.MediaContainer;
    import org.osmf.elements.VideoElement;
    import org.osmf.media.MediaPlayer;
    import org.osmf.media.URLResource;
    /**
     * The simplest OSMF application possible.
     *
     * The metadata sets the SWF size to match that of the video.
     **/
    [SWF( width="640", height="352" )]
    public class HelloWorld extends UIComponent {
        public function HelloWorld() {
            // Create the container class that displays the media.
            var container:MediaContainer = new MediaContainer();
            addChild( container );
           
            // Create the resource to play.
            var resource:URLResource = new URLResource( "http://mediapm.edgesuite.net/strobe/content/test/AFaerysTale_sylviaApostol_640_500_short.flv" );
           
            // Create the MediaElement and add it to our container class.
            var videoElement:VideoElement = new VideoElement( resource );
            container.addMediaElement( videoElement );
           
            // Set the MediaElement on a MediaPlayer.  Because autoPlay
            // defaults to true, playback begins immediately.
            var mediaPlayer:MediaPlayer = new MediaPlayer();
            mediaPlayer.media = videoElement;
        }
    }
}
Derek Santos

Quality Assurance & Testing with Flex 4

Thursday, April 15th, 2010

By Derek Santos – Consultant

Quality is becoming more and more of a concern for Rich Internet Applications. As these applications become more popular and equally more complex, it is important to take quality concerns just as seriously. With Flex 4, it has become easier to adopt a workflow that can produce applications at a level of quality that end users and stakeholders can expect. In particular, FlexUnit 4 is great tool that is well suited to Test Driven Development.

The slides available below are from a presentation I have delivered at the Toronto Flex User Group. The slides cover Quality Assurance in general, but also which tools are suited to the job. FlexUnit 4, Ant, CruiseControl, FlexCover and FlexPMD make a great combination and when integrated together can result in a highly productive and quality driven workflow.

You can download the slides and source code below.

QA & Testing Slides
Source Code

Chad Upton

How to Convert XMLList to XMLListCollection in Flex

Saturday, March 27th, 2010

By Chad Upton – Senior Consultant

Massaging data is an important part of many client applications, especially if you don’t have control over the server side.

If you want to convert an XMLList to an XMLListCollection in ActionScript, try this:

var myCollection:XMLListCollection = new XMLListCollection(myXMLList);

It is very important that you call the constructor. If you omit the new keyword, this will not work!

alaint

Printing from Flex: Part 1

Thursday, March 11th, 2010

By Alain Thibodeau – Consultant

Printing in Flex is the source of frustration for many people. Native Flex printing is good for simple print jobs, but the frustrations start when the layout becomes complex and the output becomes unpredictable. In any case, the native print API in Flex doesn’t deserve all the bad press it has been getting. We will see what can be accomplished with it and when it is time to start considering alternatives. In the first part of this series, we will first look at the native API. In the second part we will look at one of the alternatives for printing in Flex called AlivePDF.

Giving the users the ability to print from any application does not mean that they will print what is currently on the screen. It is best to not print certain areas of the application like the UI for example. It is for this reason that we normally just print the data needed in a print friendly version. Flex’s native API allows us to do that very well. It allows us to generate a printer friendly output by allowing us to select specific areas to print, create new objects for print or print the data directly. Flex actually has specific components for print that helps you achieve this. These components are the PrintDataGrid, PrintAdvancedDataGrid, PrintOLAPDataGrid.

Simple Example:

When printing in flex we want to use the classes in the mx.printing package. The main class for printing is the FlexPrintJob which is actually a wrapper of the Flash PrintJob class. The idea is to instantiate this class, start a print job, add the objects you want to add and send it to the printer. For a basic print job, the code looks like this:

var myPrintJob:FlexPrintJob = new FlexPrintJob();
myPrintJob.printAsBitmap=false;
if (myPrintJob.start()) {
myPrintJob.addObject(myObject, FlexPrintJobScaleType.NONE);
myPrintJob.send();
}

Explanation:

  1. We create an object of type FlexPrintJob
  2. We set its property of printAsBitmap to false. This will make sure that it will print as vector. The default is true which creates a bitmap image of your object. I always set this to false; I find it gives better print quality.
  3. The PrintJob’s method start will invoke the users print dialog box to open. The method returns false if the user selects cancel. If the user selects print, the method returns true and the FlexJob’s properties pageHeight and pageWidth are assigned values from the printer settings. At this point we can use these values for layout calculations if we want.
  4. Next, we need to add objects to the print job. The addObject method takes care of that. The second parameter specifies the scale type. You should use the class FlexPrintJobScaleType and its constants to specify scaling. The values are FILL_PAGE, MATCH_HEIGHT, MATCH_WIDTH, NONE, SHOW_ALL . Each call to the addObject starts a new page; this is important and becomes a little tricky if you want to add more than one object to a print page. This is discussed further below.
  5. Once the objects are added to the PrintJob, we need to send it to the printer, which is what the send method does.

Multi-object print pages

The above code demonstrated a simple example of printing in Flex that works well. Now, we move on a bit deeper and show how to add more than one object to a print page. Earlier, we added one object to the print page with the PrintJob’s addObject method, this added one object to one print page. If you want to add more than one object to one print page you need to create custom components that contain the objects you want to print. You can achieve this dynamically with ActionScript or create custom MXML components that will be instantiated and added to the display list and then to the print job. Custom components need to be on the display list in order to be added to a print job. Let’s start by creating a custom component.

<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx=http://www.adobe.com/2006/mxml
width="100%"
height="100%">

<mx:Image id="image"
source="@Embed('assets/myImage.jpg')"
width="100%"
height="100%"/>

<mx:TextArea id="description"
width="100%"
height="20%"
text="description"/>

</mx:VBox>

Now, we have our custom component. In our printing code of the main application file we need to adjust a few things.

var printJob:FlexPrintJob=new FlexPrintJob();
printJob.printAsBitmap=false;

if (printJob.start()) {
var myCustomPrintImage:PrintImage = new PrintImage();
addChild(myCustomPrintImage);
printJob.addObject(myCustomPrintImage,FlexPrintJobScaleType.SHOW_ALL);
removeChild(myCustomPrintImage);
printJob.send();

}

Explanation:

In this case we have adjusted the code by:

  1. Instantiating our custom component.
  2. Adding our custom component to the display list.
  3. Removing it from the display list to clear the memory after adding it to the print job.

This example will allow us to add more than one object to one print page and could be the start of creating a multi-page print job of several images in a database for example. I’ve always had good outcomes with the native Flex printing and this type of print job. That is, when you know the position, dimensions and number of items that will be on the page.

Printing Data

As mentioned before there are three built-in components that help print data. These components are the PrintDataGrid, PrintAdvancedDataGrid, PrintOLAPDataGrid. They come with built-in pagination and the base functionality that you need to print data grids. I will not show an example of these as it involves a lot of code and this post is meant to be kept brief. You can look at the documentation on how to use them and take time to investigate the possibilities.

Conclusion

When printing simple pages like the examples above, flex is actually quite good. Where I’ve ran into problems and bugs is when trying to create a print job that can span multiple pages and has no reoccurring layout. In more advanced printing, I’ve also used the PrintDataGrid. This component worked great for me until I had to have variable row heights which seem to break the pagination. The point I am trying to make is the same as many developer will say about flex printing; it is good for simple print jobs. Once you need to print complex reports that span multiple pages, the problems start.

There are a few other simple things that the native print API does not do which is worth mentioning. For instance, the orientation is read only. This means that you cannot specify one page to be landscape and the next to be portrait. You also do not have the option of portability, unless you have a PDF writer you can “print” too.

For these reasons, other printing options have been made available by way of third party libraries. In the next part we will look at one of the alternatives for printing in Flex. This library helps address some of the Flex printing shortcomings and is called AlivePDF. See you then!

oliverm

What’s this “1080p” thing?

Thursday, February 18th, 2010

By Oliver Merk – Principal Consultant

I get asked this question a lot. From clients wishing to display their Flex applications on a wide screen display to friends and family looking to purchase a new LCD television for the livingroom.

The short answer is that it all has to do with resolution.

Video resolution is like sandpaper; the more little grains you pack together, the smoother the surface. It’s the same with your TV screen or computer monitor. The more pixels that can be packed into each inch of the screen, the smoother and clearer images, video and text will appear.

You probably already know that a 1600×1200 computer monitor is subjectively “better” than a 640×480 screen.

Take a typical large sporting venue as an example. You’ve seen jumbo-sized screens attempt to display images and video. In years past, the picture quality was terrible; you could actually see the red, green and blue dots that made up the picture. If you squinted and used your imagination, you could possibly make out the was being displayed, especially if it involved text.

Nowadays, these large screens are a lot better. Why? Because the technology has evolved to allow the pixels (picture elements) to be packed closer together. Therefore, more pixels per inch; therefore higher resolution and image quality.

So what’s this got to do with the big signs at Fred’s Bargain TVs & Food Emporium advertising 1080p televisions?

Well, television screens work the same way as the screens in the large sports arenas. In the old days (the early 1990s), you’d be lucky to get a television to display more than more than a couple of hundred pixels in height.

Why hi-def is so cool

With the introduction of DVDs came the first wave of high definition television screens, which could display 480 pixels vertically. Wow! I remember being blown away at the clarity of these first attempts to improve our viewing pleasure.

But television manufacturers never stand still. A few years later, we were introduced to televisions with 720 pixels vertically. But if DVDs were only 480, why would you need a 720 set? Because the broadcasters were also getting into the game and allowing viewers to receive their shows at 720.

And of course, everything evolved again to where we now have televisions capable of displaying broadcast-quality video at 1080 pixels vertically and 1920 pixels horizontally. Broadcast-quality because the broadcasters now deliver at this resolution.

But what about that p and i thing?

To this point, I haven’t used the infamous “p” or “i” after these vertical pixel counts.

These letters, after the vertical resolution, such as 480i, 720p, 1080i or 1080p, refer to the way the television signal is drawn upon the screen.

Traditional television sets would fill odd-numbered lines of the screen (1, 3, 5, etc.) and then go back to the top and fill in the even-numbered lines (2, 4, 6, etc.). This happened quickly enough to fool your brain into thinking you were seeing smooth motion; around 30 frames per second.

This technique is known as interlacing the signal. The “i” for interlaced in 1080i.

With the advent of faster displays, this trick is no longer necessary; screens can now draw each line onto the screen progressively (1, 2, 3, 4, 5, etc.). So the “p” is for progressive.

The only times you may notice the difference between an interlaced and progressive display is during a fast-moving sporting event or a horizontal pan across a landscape. An interlaced signal will likely appear to stutter, skip or leave short motion trails; a progressive one will look a lot smoother.

At this point, the best display you can get at your typical electronics store is 1080p. But the screen sizes could be 40” and higher. So a 40” 1080p is going to look a lot sharper up close than a larger screen, simply because of how tightly packed the pixels are. The larger screen still look great, especially from a bit farther away.

So if you’re purchasing a new television for the livingroom, you may find that you get a better viewing experience from a 46” than a 72” (although your neighbors won’t be as jealous).

I hope that clears things up a bit. Now go and explain it to your friends and family.

oliverm

What’s New in Flex 4 – Part I

Thursday, February 18th, 2010

By Oliver Merk, Principal Consultant

Adobe’s Flex 4 platform and tools are expected to be released in the first half of 2010.

Of note:

  1. Flex Builder has been re-christened Flash Builder to promote the Flash platform.

  2. The Flex SDK has been turned on its head with the introduction of the Spark component set; skinning will never be the same (thank goodness!).

  3. A new product called Flash Catalyst CS5 will finally give designers a chance to realize their creations within the Flex framework.

In this entry, I’ll start with the theme that will have the most impact on everyone on the typical RIA team.

Designer/Developer Workflow

Adobe Flash Catalyst joins Photoshop, Illustrator and Fireworks in the RIA designer’s toolbox.

Originally a lot of us Flex developers got very excited when this new product was announced as Thermo back at Adobe MAX 2007 in Chicago. But Catalyst is distinctly not aimed at Flex application development as you might currently understand it.

Rather, Catalyst allows designers to do three critical things, which I’ll detail below:

  1. Easily import assets from the above mentioned applications for use in a Flex/AIR application.

  2. Quickly prototype an application for demonstration purposes.

  3. Create fully skinned components which can be delivered to a Flex developer for integration into a working application.

Let’s dig into these a bit further.

What the FXG!

Most professional designers work in Photoshop, Illustrator or the two in combination. Being Adobe products, it’s not hard to guess that the integration between Catalyst and these stalwarts is tight.

With Catalyst, designers tasked with creating Flex application GUIs can begin where they’re comfortable, in Photoshop, Illustrator or, my personal favorite, Fireworks.

The native formats of these programs will be importable into Catalyst as a library of assets. Files such as .PSD, .AI and .PNG can not only be imported into Catalyst, but their layers will be maintained as well.

Now the first question an astute designer will ask is, what if I want to go back to Photoshop and tweak my artwork?

Known as round-tripping, this feature is already incorporated into the latest beta builds of Catalyst. Right within Catalyst, the designer will choose to edit an asset and the appropriate program will open with the artwork ready to edit. Upon saving, the designer returns to Catalyst, which has remained open, and sees the changes immediately on screen.

But there’s another way to move assets around: using the new FXG file format.

This new format is similar to the well-intentioned Open Source SVG format we’ve heard about for many years. FXG is an archive format which contains all the information (MXML code and binary assets) required to import and export Flex components and assets using Photoshop, Illustrator, Fireworks, Catalyst. The new Flash Builder 4 can also open FXG files as imported projects.

Show me!

One of the greatest challenges in creating RIAs for clients is getting them to visualize what the completed application might look like. Currently, your options include using Flex Builder’s design mode (still hard to apply complex skinning) or mocking up something in Open Office Impress or the ubiquitous Powerpoint, which are never very accurate.

With Catalyst, designers will be able to quickly prototype not only the visual aspects of the application, but most of its behavior as well. For example, lists can be skinned and populated with temporary data, with minimal effort, so that a client can see the component as it will appear in the final application.

In fact, Catalyst is so easy to use that I wonder how long it will be before sales people realize that they can use it to help clients visualize an application and close the deal a lot quicker. I recommend Catalyst as a sales and marketing tool for those who are tasked with demonstrating the power of RIAs to potential customers but don’t have the time or resources to enlist a designer or developer to create a mock-up.

What About Us Programmers?

I said earlier that Catalyst is not a hard core developer tool and is clearly geared towards developers.

However, it will still make developers’ lives easier in several ways:

  1. For those tasked with implementing a design and given a Photoshop file, Catalyst will make short work of converting the original artwork into usable components which can be imported into Flash Builder. If you’re a Flex developer who does a lot of design implementation, Catalyst will be a game-changer for you.

  2. Catalyst gives the designer the tools to define not only the skin, but the behavioral characteristics of components. Separate components can be composed in Catalyst and delivered to the developer for integration into a Flex or AIR application. These components can be delivered as FXGs or as SWC libraries.

Here’s another great reason to check out Catalyst. I could argue that the new Flex 4 SDK is almost a whole new platform compared to Flex 3. There’s going to be a learning curve when you first try to grasp how components are composed and while investigating all the cool new features in this release. Because Catalyst generates MXML code, a developer could study this as a good introduction to how things will fit together in the new framework.

Smells good! Is it baked yet?

Catalyst is in its late beta stage and is likely to be released in the first half of 2010. While round-tripping between Catalyst and the graphics applications is almost complete, the round trip between Catalyst and Flash Builder may have to wait for a point upgrade; though I really hope they get it in for the first release.

But that shouldn’t stop you from downloading the latest beta and checking out Catalyst for yourself. You can learn more about it and download a beta from http://labs.adobe.com/technologies/flashcatalyst/.

Have fun!

Adobe Flash Catalyst Beta

Adobe Flash Catalyst Beta

Chad Upton

Secret Key Encryption Options in the as3crypto Library

Monday, February 15th, 2010

Written By: Chad Upton

The as3crypto library is an open source ActionScript 3 encryption library available from google code.

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).

In that post, I used the AES encryption algorithm but I promised a future post that talked about why. In this post, I want to revisit the secret key encryption choices in as3crypto, breaking down the choices, their strengths and weaknesses.

This guide should be used for general knowledge or to narrow down encryption methods you should consider for your project. Before making a final decision, you should deeply investigate that method to ensure it is right for your implementation.

In as3crypto, the secret key encryption choices are DES, 3DES, RC4, XTEA, AES and BlowFish.

DES

DES stands for “Data Encryption Standard.” It was developed to improve the security of US government computer systems and was completed in 1974. It has a fairly short key at 56 effective bits (8 of the 64 bits are used as a checksum and not encryption). Many encryption methods have been developed since then; it is the second fastest compared to other methods in as3crypto but it has a large number of vulnerabilities.

It should not be used unless absolutely necessary for legacy support, even then you should be considering migration to a modern cipher. As an interesting side note, there are also rumors of an NSA backdoor in this algorithm.

3DES

3DES, or “triple DES”, was developed in the late 90s as a simple way to make DES stronger and more resistant to brute force attacks (trying every possible key). It’s called “3DES” because it applies the DES algorithm three times. As you can probably guess, it’s about three times slower than DES. It does provide more security, but it’s not an ideal choice when considering what else is available. It may be required to support legacy systems.

RC4

RC4 is a fairly modern and widely used cipher method. It was developed in 1987 by Ron Rivest of RSA security (RC4 stands for “Rivest Cipher 4”). Many of you probably use this cipher everyday without realizing it. Secure website (SSL) certificates use this cipher and some wifi encryption systems use it too. It is not without its share of weaknesses, especially in certain implementations. For that reason, it has been completely deprecated by some platforms, including Microsoft .NET.

When implemented correctly, RC4 can offer a fair amount of security but there are better options available in most cases. That said, there is one case where it should at least be considered: when you have tens of megabytes of data or more to encrypt. RC4 is by far the fastest cipher method in the as3crypto library. It is about 4.5 times faster than Blowfish (third fastest in library), but keep in mind it is slightly less secure than Blowfish.

XTEA

XTEA has fewer vulnerabilities than RC4, so it is slightly more secure. But, this is the slowest encryption method in the as3crypto library. Frankly, the only case where I could see this being used in ActionScript is when you’re interacting with other systems that use XTEA encryption. If you’re developing a new system, choose one of the following methods.

AES

AES is one of the best general purpose secret key encryption methods in as3crypto. Like I mentioned above, there may be cases where another method is more appropriate, but AES is going to be the method of choice in many cases, particularly because many other systems that your application may interact with will use it.

It has a lot of credibility because it is the standard encryption used by the US government and the first publically available cipher approved by the NSA. It is fast and secure, although it does have some known weaknesses that can usually be protected by prevented brute force attacks. This method should not be overlooked.

Blowfish

Blowfish was developed in 1993 by Bruce Schneier, who has developed many other cryptographic algorithms, written several articles and books on security, and also publishes a free monthly security newsletter called CRYTPO-GRAM, which I subscribe to and recommend.

In as3crypto, Blowfish 256 performs more than twice as fast as AES 256. It is also capable of using a 448 bit key, although the as3crypto implementation uses a 256 bit key. When compared to AES 256, Blowfish gives you slightly better security since it has no known cryptanalysis. It’s may not be as widely used as AES, but for great speed and security, it should not be overlooked. For many projects, this is an excellent choice of encryption.

Conclusion

If you don’t have any legacy system requirements, you should start by looking at Blowfish or AES encryption. One of these is likely going to meet your requirements, especially if you’re working with less than a megabyte of data. With large amounts of data these two may be too slow, so be sure to look at RC4 in more detail — it’s really fast. All of the others are likely going to be used because you’re working with a legacy system that requires them.

Chad Upton

Encryption and Decryption with as3crypto Library

Thursday, December 17th, 2009

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