加解密代码
package
{
import flash.display.Shape;
import flash.display.Sprite;
import flash.utils.ByteArray;
public class Test extends Sprite {
public function Test() {
var dataStr:String = "Today's weather is good.";
var data:ByteArray = new ByteArray();
data.writeMultiByte(dataStr, "utf-8");
var keyStr:String = "abcxyz123";
var key:ByteArray = new ByteArray();
key.writeMultiByte(keyStr, "utf-8");
trace("data:", dataStr);
trace("key:", keyStr);
//加密
var encryptData:ByteArray = XXTEA.encrypt(data, key);
var content:String = Base64.encodeByteArray(encryptData);
trace("encode: " + content);
//解密
encryptData = Base64.decodeToByteArray(content);
var sourceBtyes:ByteArray = XXTEA.decrypt(encryptData, key);
var sourceStr:String = sourceBtyes.toString();
trace("decode: " + sourceStr );
}
}
}
XXTEA加解密用到了Base64,以下是XXTEA和Base64的代码
XXTEA的代码
package
{
import flash.utils.ByteArray;
import flash.utils.Endian;
public class XXTEA {
private static const delta:uint = uint(0x9E3779B9);
private static function LongArrayToByteArray(data:Array, includeLength:Boolean):ByteArray {
var length:uint = data.length;
var n:uint = (length - 1) << 2;
if (includeLength) {
var m:uint = data[length - 1];
if ((m < n - 3) || (m > n)) {
return null;
}
n = m;
}
var result:ByteArray = new ByteArray();
result.endian = Endian.LITTLE_ENDIAN;
for (var i:uint = 0; i < length; i++) {
result.writeUnsignedInt(data[i]);
}
if (includeLength) {
result.length = n;
return result;
}
else {
return result;
}
}
private static function ByteArrayToLongArray(data:ByteArray, includeLength:Boolean):Array {
var length:uint = data.length;
var n:uint = length >> 2;
if (length % 4 > 0) {
n++;
data.length += (4 - (length % 4));
}
data.endian = Endian.LITTLE_ENDIAN;
data.position = 0;
var result:Array = [];
for (var i:uint = 0; i < n; i++) {
result[i] = data.readUnsignedInt();