Base64 Encoding in ActionScript
ActionScript provides built-in support for base64 encoding/decoding through the Base64Encoder
and Base64Decoder
classes in the mx.utils
package.
package {
import flash.display.Sprite;
import flash.utils.ByteArray;
import mx.utils.Base64Encoder;
import mx.utils.Base64Decoder;
public class Base64EncodingExample extends Sprite {
public function Base64EncodingExample() {
// Here's the string we'll encode/decode.
var data:String = "abc123!?$*&()'-=@~";
// ActionScript uses Base64Encoder for encoding
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(data);
var sEnc:String = encoder.toString();
trace(sEnc);
// Decoding using Base64Decoder
var decoder:Base64Decoder = new Base64Decoder();
decoder.decode(sEnc);
var sDec:String = decoder.toByteArray().toString();
trace(sDec);
trace();
// ActionScript doesn't have a built-in URL-safe Base64 encoding
// You would need to implement it yourself or use a third-party library
// Here's a simple implementation for demonstration:
var uEnc:String = encodeURLSafe(data);
trace(uEnc);
var uDec:String = decodeURLSafe(uEnc);
trace(uDec);
}
private function encodeURLSafe(input:String):String {
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(input);
return encoder.toString().replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
private function decodeURLSafe(input:String):String {
var decoder:Base64Decoder = new Base64Decoder();
input = input.replace(/-/g, "+").replace(/_/g, "/");
while (input.length % 4 != 0) {
input += "=";
}
decoder.decode(input);
return decoder.toByteArray().toString();
}
}
}
To run this ActionScript program, you would typically compile it into a SWF file and run it in a Flash Player or AIR runtime environment. The output would be similar to:
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
Note that ActionScript’s built-in Base64 encoding is similar to the standard encoding in other languages. For URL-safe encoding, we’ve implemented a simple conversion that replaces +
with -
, /
with _
, and removes padding =
characters. This is a common approach for making Base64 strings safe for use in URLs.
Unlike some other languages, ActionScript doesn’t provide a built-in URL-safe Base64 encoding, so you might need to implement it yourself or use a third-party library in real-world applications.