views:

115

answers:

4

I want to encode / decode a string in AS3:

var string:String = "This is an text";

encode(string) will give for example: "yuioUasUenUwdfr"

decode(encoded(string)) will give: "This is an text";

It does not have to be secure or anything.

Thnx!

+1  A: 

I would suggest either base64 or rot13 encoding. There are many AS3 implementations for each. Google will provide.

spender
Allard
This is the lib he's referring to: http://github.com/mikechambers/as3corelib
UltimateBrent
A: 

Another option is using a XOR cypher, with a key. This method is totally breakable, of course, but it takes a bit more work, so for obscuring your text it should be fine.

Here's a simple implementation. (It uses hurlant's Base64 encoder; This is just to make it binary-safe, not to add more obscurity)

import com.hurlant.util.Base64;

function applyXor(inputBuffer:ByteArray,key:String):ByteArray {
    var outBuffer:ByteArray = new ByteArray();

    var keysBuffer:ByteArray = new ByteArray();
    keysBuffer.writeUTFBytes(key);

    var offset:int = 0;
    var inChar:int;
    var outChar:int;
    var bitMask:int;

    while(inputBuffer.bytesAvailable) {
        offset  = inputBuffer.position % keysBuffer.length;
        inChar  = inputBuffer.readUnsignedByte();

        bitMask = keysBuffer[offset];

        outChar = bitMask ^ inChar;     
        outBuffer.writeByte(outChar);

    }

    return outBuffer;
}

function encode(input:String,key:String):String {
    var inputBuffer:ByteArray = new ByteArray();
    inputBuffer.writeUTFBytes(input);
    inputBuffer.position = 0;
    var out:ByteArray = applyXor(inputBuffer,key);
    return Base64.encodeByteArray(out);
}

function decode(input:String,key:String):String {
    var inputBuffer:ByteArray = Base64.decodeToByteArray(input);
    var out:ByteArray = applyXor(inputBuffer,key);
    out.position = 0;
    return out.readUTFBytes(out.length);
}

var str:String = "This is some text. Let's add non-ascii chars like Ñ,à,ü, etc, just to test it.";
var key:String = "whatever &^%$#";
var encoded:String = encode(str,key);
var decoded:String = decode(encoded,key);

trace(encoded);
trace(decoded);
trace(decoded == str);
Juan Pablo Califano
A: 

Thnx guys .. got it up and running with com.hurlant.util.Base64;

Allard
A: 

if you're building an AIR application, you can encrypt your data with the EncryptedLocalStore class.

TheDarkInI1978