PageRenderTime 183ms CodeModel.GetById 101ms app.highlight 5ms RepoModel.GetById 75ms app.codeStats 0ms

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

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
ActionScript | 86 lines | 65 code | 7 blank | 14 comment | 6 complexity | a242a511223c6b4c66f8812633d278c9 MD5 | raw file
 1/**
 2 * ECBMode
 3 * 
 4 * An ActionScript 3 implementation of the ECB confidentiality mode
 5 * Copyright (c) 2007 Henri Torgemane
 6 * 
 7 * See LICENSE.txt for full license information.
 8 */
 9package com.hurlant.crypto.symmetric
10{
11	import flash.utils.ByteArray;
12	import com.hurlant.util.Memory;
13	import com.hurlant.util.Hex;
14	
15	/**
16	 * ECB mode.
17	 * This uses a padding and a symmetric key.
18	 * If no padding is given, PKCS#5 is used.
19	 */
20	public class ECBMode implements IMode, ICipher
21	{
22		private var key:ISymmetricKey;
23		private var padding:IPad;
24		
25		public function ECBMode(key:ISymmetricKey, padding:IPad = null) {
26			this.key = key;
27			if (padding == null) {
28				padding = new PKCS5(key.getBlockSize());
29			} else {
30				padding.setBlockSize(key.getBlockSize());
31			}
32			this.padding = padding;
33		}
34		
35		public function getBlockSize():uint {
36			return key.getBlockSize();
37		}
38		
39		public function encrypt(src:ByteArray):void {
40			padding.pad(src);
41			src.position = 0;
42			var blockSize:uint = key.getBlockSize();
43			var tmp:ByteArray = new ByteArray;
44			var dst:ByteArray = new ByteArray;
45			for (var i:uint=0;i<src.length;i+=blockSize) {
46				tmp.length=0;
47				src.readBytes(tmp, 0, blockSize);
48				key.encrypt(tmp);
49				dst.writeBytes(tmp);
50			}
51			src.length=0;
52			src.writeBytes(dst);
53		}
54		public function decrypt(src:ByteArray):void {
55			src.position = 0;
56			var blockSize:uint = key.getBlockSize();
57			
58			// sanity check.
59			if (src.length%blockSize!=0) {
60				throw new Error("ECB mode cipher length must be a multiple of blocksize "+blockSize);
61			}
62			
63			var tmp:ByteArray = new ByteArray;
64			var dst:ByteArray = new ByteArray;
65			for (var i:uint=0;i<src.length;i+=blockSize) {
66				tmp.length=0;
67				src.readBytes(tmp, 0, blockSize);
68				
69				key.decrypt(tmp);
70				dst.writeBytes(tmp);
71			}
72			padding.unpad(dst);
73			src.length=0;
74			src.writeBytes(dst);
75		}
76		public function dispose():void {
77			key.dispose();
78			key = null;
79			padding = null;
80			Memory.gc();
81		}
82		public function toString():String {
83			return key.toString()+"-ecb";
84		}
85	}
86}