Actionscript 2.0: Base64 Encoder

I've gotten a bit of a chance to play around with the Flex 2 Alpha, and I have to say - I'm pretty impressed. I like what Macromedia has done with it, and I'm sure it will get better as it gets closer to RTM. I'm cooking up something that will hopefully be pretty cool...probably just saying that has relegated it to NTBC status, but I've got my fingers crossed.

In the meanwhile, here's something I've had kicking around for a bit: an AS 2.0 Base 64 Encoder. It's ported more or less directly from Stephen Ostermiller's Javascript Base 64 Encoder. I was using it to play around with Http Authentication in Flash, which requires username/passwords to be sent Base 64 encoded. The main port was pulling it from being a bunch of global functions into a class, encoding and decoding through Static methods.

Download below the fold...

How does this relate to Flex, you ask? Well, digging around through the class library, I noticed that MM added a Base64Encoder class. Which is nice. So since this will be become obsolescent within the next year, I thought I get over procrastinating releasing it.

To use (note: I did not put the class into a package - if you do, you'll obviously need to import or fully quantify the references):

  1. var unEncoded:String = "This is a string";
  2. var encoded:String = Base64.Encode( unEncoded );
  3. var decoded:String = Base64.Decode( encoded );

I've also stuck a StringReplaceAll method onto the class, to avoid having to package it with a StringUtil class. Obviously, you can pull that out to use your own, but it's probably not worth the effort...

Todo: Fix the issue with line breaks (technically, Base64 encoded string cannot contain line breaks, and it should strip them out [if I remember correctly - it's been a while since I worked on this]).

Download: Base64.as.

Share me: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati

Comments (45) left to “Actionscript 2.0: Base64 Encoder”

  1. subHero wrote:

    Nice, just thought about implementing a Base64 En-/Decoder in as3 yesterday. Dropped it ;)

    Line breaks:
    By specification (as far as i can remember) it is totally legitimate to insert non-base64 characters into the stream (like linebreaks in order to put the specified, proposed length limit of 76 chars for each line into effect). Technically the encoded string will contain control/whitespace characters then. It is in the decoder’s responsibility to strip out all non-base64 characters before “actual” decoding. That should be an easy hack ;)

    I am probably deaf, dumb and blind on this one, but:
    How did you want to achieve the http-authentication? By which means did you try to set the http-authentication header entry for the request by flash?

    OTT: Nice blog, serious work, sweet little fella :)
    Keep it up!

  2. jason wrote:

    Thanks. :)
    I was implementing the Http Auth via AddRequestHeader() on either or both of the XML and LoadVars classes.

  3. Stephen Ostermiller wrote:

    I don’t know anything about ActionScript, but that looks like a nice port of my libraries. I put up a page about it on my site as well:
    http://ostermiller.org/base64_actionscript.html

  4. jason wrote:

    Thanks, Stephen!

  5. programental.org » Blog Archive » Simple Crypto wrote:

    […] ase64. Алгоритъма за Base64 кодиране, който изтеглих от Jasson Nussbaum, се придържа стриктно към специфи […]

  6. Brian Meidell’s Blog » HTTP Authentication with Flash wrote:

    […] arts of examples, but not an actual working example, so here it is. First of all, get the actionscript Base64 encoder class. Put it in your classpath or the same directory as your .fla file. Then d […]

  7. Webudviklerne » Blog-arkiv » LoadVars med login/password wrote:

    […] er du data fra flash fra et script der ligger under http authentication beskyttelse. Hent ActionScript base64 encoder klassen. Smid den i samme mappe som din .fla fil. var loadvars = new LoadVars […]

  8. subHero wrote:

    so i put up my own as3-simple-implementation using ByteArray, anyway.
    you can check it out at
    http://www.flashkit.com/board/showthread.php?t=655324&page=4

    still, big UP to you. it got me learning :)

    cheers
    -sh

    ps: i got a nice little fellow as well now (* 28th november, 2005), so i’m feelin’ you ;)

  9. jason wrote:

    Sweet. Thanks. :)

  10. e-sense wrote:

    Hello, can somebody answer about ” é à ç é … ” diacritics, I tried to use this class, but it just drop “non-english” caracters

  11. e-sense wrote:

    found solution using it with escape / unescape, thanks for class, working great

  12. jason wrote:

    Your solution was to escape prior to encoding, and unescape after encoding?

  13. e-sense wrote:

    yep ;-)

  14. Zarate wrote:

    Hi!

    I’m finding differences between your enconding and other encoders. You can make a test with these compilers:

    http://www.motobit.com/util/base64-decoder-encoder.asp
    http://www.secretmaker.com/emailsecurer/base64coder/default.html

    Try to encode the string “word\+word” (without quotes). Your encoder throws:

    d29yZCU1Q3dvcmQ=

    And the other two:

    d29yZFwrd29yZA==

    I don’t know if this is a problem of the original work or it’s a problem of your port. I’ll try to find it.

    Thank you!

  15. Zarate wrote:

    Hi

    I think it’s a problem of the AS2 port, you can check it in the original JavaScript page:

    http://www.ostermiller.org/calc/encode.html

    The original one is throwing the correct translation. I’m going to take a look to it because also it doesn’t compile with MTASC 1.11.

    Bye!

  16. jason wrote:

    Hey - I’ll take a look into that when I can. I’ve been a bit busy lately. Thanks for the heads up.

  17. Adrian wrote:

    Hello,
    I recently had to deal with some protocols that required me to send base64-encoded strings that contained several null characters as delimiters between elements.
    Unfortunetly flash truncates the string at the very first null character it encounters. That leaves me with no option to properly encode such a string.
    Is there a way I can use a “null character substitute” together whith this class ?
    Thanks!!!

  18. Indefinite Articles » Base64 Encoding for ActionScript 3/Flex 2.0 wrote:

    […] I updated this Base64 Encoder to work with ActionScript 3 for Flex 2.0 Beta 3. […]

  19. Rostislav Siryk wrote:

    Jason, thank you for so useful class! I’ve already used it to send order data from flash application to payment section and all works good. At least perl Base64 library is compatible with yours :)

    However, I’ve detected some issues: when calling StringReplaceAll method, you use backslashes before plus symbol in its “find” parameter:

    Line 117: str = StringReplaceAll( str, “\+”, ” ” );

    Line 126: str = StringReplaceAll( str, “\+”, “%2B” );

    Flash IDE Compiler (aka MMC) compiles this, but MTASC compiler which I use (and a lot of people use it too) don’t want to compile this due to slashes (the exact error message is “syntax error Invalid character ‘+’”).

    So I removed slashes from both lines 117 and 126 ans MTASC started compiling your class perfeclty as well as MMC. And all seems to works good (pretty complicated url containing ‘plus’ symbols encoded/decoded succesfully (’plus’ symbols didn’t disappear)).

    So I’ve updated your class for use with MTASC ;-)

  20. Kevin McGarrity wrote:

    Jason/Anyone,
    Can this Base64 class be used to decode .jpg image data, pulled from an XML file as Base64 encoded data?
    Thanks,
    Kevin.

  21. Kevin McGarrity wrote:

    Sorry, this has all left me totally confused.

    I’ve pulled in the Base64 encoded data into my Flash app from the XML file and it’s now stored in a variable called ‘Base64′. How do I go about converting this to a .jpg image using this Base64 class? Which function is used to decode the Base64 data I have stored in my Base64 variable? Is it the ‘Decode’ function or the ‘decodeBase64′ function?

    I relatively new to Flash, hence the confusion . . . so any help would be greatly appreciated!

  22. Kevin McGarrity wrote:

    Got it!

    I had the variable that I was trying to decode named as ‘Base64′ (i.e. var Base64 = xmlBase64.toString();) therefore it was causing the code to clash (for want of a better phrase) with the name of the class itself, thus throwing up an undefined error in the output panel.

    Anyway, my issue is resolved now. Thanks for developing such an excellent tool Jason!

  23. jason wrote:

    Hey Kevin,
    Glad you got it working. (heh - I know it’s been a while, but I thought I should respond…)

  24. Leo wrote:

    Hello there,

    I’m new to Flash and I need to convert an Audio object into a base64 string to be sent to my server via XML-RPC. Would you mind showing me how to convert a Sound object into base64 using your methods?

    Thanks in advance,

    Leo

  25. kanu wrote:

    Hi Kevin,
    I’m facing the same problem which you resolved.
    Can you pls explain what u did to decode the image which you are getting from XML in base-64.

  26. kanu wrote:

    Its done
    Thanks for developing such an excellent tool Jason!

  27. kanu wrote:

    i wanna encode a whole image in to base-64 instead of a string?
    Is there is any way of doing this.
    As i see this class encodes a string not an image.

  28. jason wrote:

    Kanu - you’re probably better off going AS3 to do that. Check these links:

    http://www.kaourantin.net/2005/10/png-encoder-in-as3.html
    http://www.5etdemi.com/blog/archives/2006/12/as3-png-encoder-faster-better/

    Or, for the whole enchilada (or, rather, to find your enchilada):

    http://www.google.ca/search?q=actionscript+3+png+encoder&

  29. Mike wrote:

    jason,

    got a quick one about implementing this one on AS 2.0 for flash 7, I dont have flash 8. I am running into problems, here is my quick sample:

    import Base64;

    var unEncoded:String = “This is a string”;
    var encoded:String = Base64.Encode(unEncoded);
    trace(”here ” + encoded);

    but encoded turns out to be undefined

    anything I am missing?

    thanks

  30. jason wrote:

    Mike,
    Hrm. Have you ensured that the Base64.as file is in your classpath? (By default having it in the same directory as your .fla should suffice…) Off the top of my head, I can’t think of another reason for that bombing like that.

    One other possibility - you shouldn’t need the import statement (although I don’t believe it hurts).

    If that doesn’t fix it, drop me a line (and maybe a zip of your sample project structure) and I’ll see if I can come up with anything else. It should work in Flash 7 - I don’t think there is anything that you specifically need 8 for. In fact, I believe I wrote it for 7, though I can’t remember anymore…

  31. Mike wrote:

    Jason, found the problem, I had the AS file renamed to something else. I renamed the AS file Base64-v2implemen.as

    I thought that you import the class not the file. Silly me. I had the fla and AS file in the same dir. Works like a charm now
    Sorry, I am fairly new to AS and flash. I feel like an idiot.

    Again, a million thank yous

  32. jason wrote:

    Yeah, flash matches the class to the filename (or vice-versa, depending on how you look at it). Glad you got it worked out…

  33. Mark wrote:

    Hi Jason,

    Is it possible to take base64 data, decode it with your class and then somehow transfer that to a BitmapData object?

    Basically I want base64 encoded image data loaded into flash to be able to display as the image itself.

    Thanks,

    Mark.

  34. David Carter wrote:

    Hi Jason:

    I found a bug in your Base64 class that I appear to have fixed — although the fix was so easy it makes me wonder if I’ve broken something else and that’s why you have it written the way you do. Basically I was finding ntos was not always converting the number to a string properly in all cases — it appears “unescape” is returning empty strings for certain hex values, like %d0 for example.

    To fix it, I replaced ntos with the following:

    private function ntos( n:Number ) : String
    {
    return (String.fromCharCode(n));
    }

    This seems to work — at least I haven’t broken it yet. I’d love hear from you about why you didn’t use this approach — I’m hoping it just didn’t occur to you and there isn’t anything broken about it.

    Regards;

    DaC

  35. David Carter wrote:

    typo in prev comment — that should be %d0 not %do.

    DaC

  36. shawn wrote:

    Could anybody show me a working version of this? i do not understand it completely. just like a test page that it is set up on so i can see it in action? pleasE?

  37. Daniel Phillips wrote:

    Hello, nice interesting blog. I love actionscript, in fact i have just made me a site on it, would you be interested in exchanging links with my site?

    http://www.actionscriptcoding.com

    Daniel

  38. Lee Probert wrote:

    dude, you still got this Base64 class … I need an AS2 one.

    :-)

  39. jason wrote:

    Hey - fixed the issue. No mime-type set up for .as, so the server wasn’t returning it. It’s still up there - you can now download.

    Cheers.

  40. Philipp wrote:

    This comes up early when googling for base64 and ActionScript 2, and you share the annoying habit of many a developer of making people download the source to find out it’s GPL.

    I think it’s a fair comment to point people who need a base64 class that can be meaningfully used in a commercial Flash project to Steve Webster’s implementation at http://dynamicflash.com/goodies/base64/ (MIT licence)

  41. Flash Lite en basic HTTP auth at noCreativity.com wrote:

    […] Dit kan blijkbaar heel makkelijk opgelost worden, door gebruik te maken van de addRequestHeaders method (die zowel voor de XML class, de webservice class, alsook voor LoadVars class beschikbaar is), en de Base64 class (download hier). […]

  42. Omar Borjas wrote:

    Fantastic work man. This is a work of art!

  43. Justin wrote:

    i should get this going!
    http://www.noisydesign.com

  44. Secure your Flash-PHP connection | Martic.net wrote:

    […] For the above example you’ll need actionscript Base64 encoder class. […]

  45. Christina wrote:

    Thanks a lot!!
    From Ukraine :)

Post a Comment

*Required
*Required (Never published)