PageRenderTime 108ms CodeModel.GetById 96ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/js/lib/Socket.IO-node/support/socket.io-client/lib/vendor/web-socket-js/flash-src/com/hurlant/crypto/symmetric/XTeaKey.as

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
ActionScript | 94 lines | 71 code | 11 blank | 12 comment | 3 complexity | c5442dd20e405b5d3272eb04e1ab9565 MD5 | raw file
 1/**
 2 * XTeaKey
 3 * 
 4 * An ActionScript 3 implementation of the XTea algorithm
 5 * Copyright (c) 2007 Henri Torgemane
 6 * 
 7 * See LICENSE.txt for full license information.
 8 */
 9package com.hurlant.crypto.symmetric
10{
11	import com.hurlant.crypto.prng.Random;
12	import com.hurlant.util.Memory;
13	
14	import flash.utils.ByteArray;
15	
16	
17	public class XTeaKey implements ISymmetricKey
18	{
19		public const NUM_ROUNDS:uint = 64;	
20		private var k:Array;
21
22		public function XTeaKey(a:ByteArray) {
23			a.position=0;
24			k = [a.readUnsignedInt(),a.readUnsignedInt(),a.readUnsignedInt(),a.readUnsignedInt()];
25		}
26		/**
27		 * K is an hex string with 32 digits.
28		 */
29		public static function parseKey(K:String):XTeaKey {
30			var a:ByteArray = new ByteArray;
31			a.writeUnsignedInt(parseInt(K.substr(0,8),16));
32			a.writeUnsignedInt(parseInt(K.substr(8,8),16));
33			a.writeUnsignedInt(parseInt(K.substr(16,8),16));
34			a.writeUnsignedInt(parseInt(K.substr(24,8),16));
35			a.position = 0;
36			return new XTeaKey(a);
37		}
38		
39		public function getBlockSize():uint {
40			return 8;
41		}
42
43		public function encrypt(block:ByteArray, index:uint=0):void {
44			block.position = index;
45			var v0:uint = block.readUnsignedInt();
46			var v1:uint = block.readUnsignedInt();
47			var i:uint;
48			var sum:uint =0;
49			var delta:uint = 0x9E3779B9;
50			for (i=0; i<NUM_ROUNDS; i++) {
51				v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
52				sum += delta;
53		        v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
54			}
55			block.position-=8;
56			block.writeUnsignedInt(v0);
57			block.writeUnsignedInt(v1);
58		}
59		
60		public function decrypt(block:ByteArray, index:uint=0):void {
61			block.position = index;
62			var v0:uint = block.readUnsignedInt();
63			var v1:uint = block.readUnsignedInt();
64			var i:uint;
65			var delta:uint = 0x9E3779B9;
66			var sum:uint = delta*NUM_ROUNDS;
67			for (i=0; i<NUM_ROUNDS; i++) {
68				v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
69				sum -= delta;
70				v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
71			}
72			block.position-=8;
73			block.writeUnsignedInt(v0);
74			block.writeUnsignedInt(v1);
75		}
76
77		public function dispose():void {
78			//private var k:Array;
79			var r:Random = new Random;
80			for (var i:uint=0;i<k.length;i++) {
81				k[i] = r.nextByte();
82				delete k[i];
83			}
84			k = null;
85			Memory.gc();
86		}
87
88		public function toString():String {
89			return "xtea";
90		}
91	}
92	
93
94}