Encode decode in Flex using Base64


I am developing a flex AIR application in which I will store some data in a text file on user’s local machine. But the data is somehow private and confidential so I thought I should encrypt that data. I searched a bit how to encrypt the data and my search result made me happy, I come to know that Flex has already a capability to encrypt and decrypt the string using base64 encoding. Its wonderful!

First you will have to import to classes

import mx.utils.Base64Encoder;
import mx.utils.Base64Decoder;

Now first create a encoder object

private var myEncoder:Base64Encoder = new Base64Encoder();

Call the encode method

myEncoder.encode("I'm being encoded"); // It will encode the characters of  string in Base64 and add the result to an internal buffer.

// now to access the encoded string use this
var encodedText:String = myEncoder.toString();

In encodedText variale you will have the encoded string, yes and that text I saved to my text file.

Now to read again the original text we’ll will have to decode the encoded string, so what you have to do is

First create the decoder object

private var myDecoder:Base64Decoder = new Base64Decoder();

Call the decode method


here we just pass the Base64 encoded string as parameter for decode method, again the result will be stored in an internal buffer.

Now to get the original string first we’ll have to get the encoded string in ByteArray and than we will convert it to string like in this way

var decodedByteArr:ByteArray = myDecoder.toByteArray();

var decodedText = decodedByteArr.toString();

That’s it.

Now lets say there is a image which is base64 encoded, so how we can convert the encoded string to image. For that use this

img.load(decodedByteArr); // in the load method pass the ByteArray

<mx:Image id=”img” />

That’s it, as usual so simple.