PageRenderTime 193ms CodeModel.GetById 81ms app.highlight 5ms RepoModel.GetById 106ms app.codeStats 0ms

/flash-src/third-party/com/hurlant/crypto/hash/HMAC.as

http://github.com/gimite/web-socket-js
ActionScript | 82 lines | 56 code | 6 blank | 20 comment | 8 complexity | c96c9bc0e0b64eed7e2d8c27dc29c561 MD5 | raw file
 1/**
 2 * HMAC
 3 * 
 4 * An ActionScript 3 implementation of HMAC, Keyed-Hashing for Message
 5 * Authentication, as defined by RFC-2104
 6 * Copyright (c) 2007 Henri Torgemane
 7 * 
 8 * See LICENSE.txt for full license information.
 9 */
10package com.hurlant.crypto.hash
11{
12	import flash.utils.ByteArray;
13	import com.hurlant.util.Hex;
14	
15	public class HMAC implements IHMAC
16	{
17		private var hash:IHash;
18		private var bits:uint;
19		
20		/**
21		 * Create a HMAC object, using a Hash function, and 
22		 * optionally a number of bits to return. 
23		 * The HMAC will be truncated to that size if needed.
24		 */
25		public function HMAC(hash:IHash, bits:uint=0) {
26			this.hash = hash;
27			this.bits = bits;
28		}
29		
30
31		public function getHashSize():uint {
32			if (bits!=0) {
33				return bits/8;
34			} else {
35				return hash.getHashSize();
36			}
37		}
38		
39		/**
40		 * Compute a HMAC using a key and some data.
41		 * It doesn't modify either, and returns a new ByteArray with the HMAC value.
42		 */
43		public function compute(key:ByteArray, data:ByteArray):ByteArray {
44			var hashKey:ByteArray;
45			if (key.length>hash.getInputSize()) {
46				hashKey = hash.hash(key);
47			} else {
48				hashKey = new ByteArray;
49				hashKey.writeBytes(key);
50			}
51			while (hashKey.length<hash.getInputSize()) {
52				hashKey[hashKey.length]=0;
53			}
54			var innerKey:ByteArray = new ByteArray;
55			var outerKey:ByteArray = new ByteArray;
56			for (var i:uint=0;i<hashKey.length;i++) {
57				innerKey[i] = hashKey[i] ^ 0x36;
58				outerKey[i] = hashKey[i] ^ 0x5c;
59			}
60			// inner + data
61			innerKey.position = hashKey.length;
62			innerKey.writeBytes(data);
63			var innerHash:ByteArray = hash.hash(innerKey);
64			// outer + innerHash
65			outerKey.position = hashKey.length;
66			outerKey.writeBytes(innerHash);
67			var outerHash:ByteArray = hash.hash(outerKey);
68			if (bits>0 && bits<8*outerHash.length) {
69				outerHash.length = bits/8;
70			}
71			return outerHash;
72		}
73		public function dispose():void {
74			hash = null;
75			bits = 0;
76		}
77		public function toString():String {
78			return "hmac-"+(bits>0?bits+"-":"")+hash.toString();
79		}
80		
81	}
82}