flash as3 string encode decode

时光怂恿深爱的人放手 提交于 2019-12-12 03:55:19

问题


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.


回答1:


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




回答2:


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



回答3:


Thanks, guys! Got it up and running with com.hurlant.util.Base64.




回答4:


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



来源:https://stackoverflow.com/questions/3868375/flash-as3-string-encode-decode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!