import MD5;
class authcode {
	public static var authkey:String = "supesite";
	
	public function code(opString:String, op:String):String {
		var key:String = MD5.calculate(authkey);
		var keylength:Number = key.length;
		var s:String = (op == "DECODE") ? decode(opString) : (MD5.calculate(opString+key).substr(0, 8)+opString);
		var slength:Number = s.length;
		var rndkey:Array = new Array();
		var box:Array = new Array();
		var str:String = "";
		var stmp:String;
		var tmp:Number;
		for(var i=0;i<=255;i++) {
			stmp = String(key.charAt(i%keylength));
			rndkey[i] = stmp.charCodeAt();
			box[i] = i;
		}
		for(var j =0,i =0;i<256;i++) {
			j = (j+box[i]+rndkey[i]) % 256;
			tmp = box[i];
			box[i] = box[j];
			box[j] = tmp;
		}
		for(var a =0,j =0,i=0;i<slength;i++) {
			a = (a+1)%256;
			j = (j+box[a])%256;
			tmp = box[a];
			box[a] = box[j];
			box[j] = tmp;
			str += String.fromCharCode(s.charAt(i).charCodeAt() ^ (box[(box[a]+box[j]) %256]));
		}
		if(op == "DECODE") {
			if(str.substr(0, 8) == MD5.calculate(str.substr(8) + key).substr(0, 8)) {
				return str.substr(8);
			} else {
				return "";
			}
		} else {
			return encode(str);
		}
	}
	
	private static function encode(opString:String):String {
		var str=opString;
		var base64s:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
		var bits, dual, i:Number = 0, encOut = '';
		while (str.length>=i+3) {
			bits = (str.charCodeAt(i++) & 0xff) << 16 | (str.charCodeAt(i++) & 0xff) << 8 | str.charCodeAt(i++) & 0xff;
			encOut += base64s.charAt((bits & 0x00fc0000) >> 18)+base64s.charAt((bits & 0x0003f000) >> 12)+base64s.charAt((bits & 0x00000fc0) >> 6)+base64s.charAt((bits & 0x0000003f));
		}
		if (str.length-i>0 && str.length-i<3) {
			dual = Boolean(str.length-i-1);
			bits = ((str.charCodeAt(i++) & 0xff) << 16) | (dual ? (str.charCodeAt(i) & 0xff) << 8 : 0);
			encOut += base64s.charAt((bits & 0x00fc0000) >> 18)+base64s.charAt((bits & 0x0003f000) >> 12)+(dual ? base64s.charAt((bits & 0x00000fc0) >> 6) : '=')+'=';
		}
		return encOut;
	}
	
	private static function decode(opString:String):String {
		var str = opString;
		var base64s:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
		var bits, decOut = '', i:Number = 0;
		for (i=0; i<str.length; i += 4) {
			bits = (base64s.indexOf(str.charAt(i)) & 0xff) << 18 | (base64s.indexOf(str.charAt(i+1)) & 0xff) << 12 | (base64s.indexOf(str.charAt(i+2)) & 0xff) << 6 | base64s.indexOf(str.charAt(i+3)) & 0xff;
			decOut += String.fromCharCode((bits & 0xff0000) >> 16, (bits & 0xff00) >> 8, bits & 0xff);
		}
		return decOut;
	}
}