4 * An ActionScript 3 implementation of HMAC, Keyed-Hashing for Message
\r
5 * Authentication, as defined by RFC-2104
\r
6 * Copyright (c) 2007 Henri Torgemane
\r
8 * See LICENSE.txt for full license information.
\r
10 package com.hurlant.crypto.hash
\r
12 import flash.utils.ByteArray;
\r
13 import com.hurlant.util.Hex;
\r
15 public class HMAC implements IHMAC
\r
17 private var hash:IHash;
\r
18 private var bits:uint;
\r
21 * Create a HMAC object, using a Hash function, and
\r
22 * optionally a number of bits to return.
\r
23 * The HMAC will be truncated to that size if needed.
\r
25 public function HMAC(hash:IHash, bits:uint=0) {
\r
31 public function getHashSize():uint {
\r
35 return hash.getHashSize();
\r
40 * Compute a HMAC using a key and some data.
\r
41 * It doesn't modify either, and returns a new ByteArray with the HMAC value.
\r
43 public function compute(key:ByteArray, data:ByteArray):ByteArray {
\r
44 var hashKey:ByteArray;
\r
45 if (key.length>hash.getInputSize()) {
\r
46 hashKey = hash.hash(key);
\r
48 hashKey = new ByteArray;
\r
49 hashKey.writeBytes(key);
\r
51 while (hashKey.length<hash.getInputSize()) {
\r
52 hashKey[hashKey.length]=0;
\r
54 var innerKey:ByteArray = new ByteArray;
\r
55 var outerKey:ByteArray = new ByteArray;
\r
56 for (var i:uint=0;i<hashKey.length;i++) {
\r
57 innerKey[i] = hashKey[i] ^ 0x36;
\r
58 outerKey[i] = hashKey[i] ^ 0x5c;
\r
61 innerKey.position = hashKey.length;
\r
62 innerKey.writeBytes(data);
\r
63 var innerHash:ByteArray = hash.hash(innerKey);
\r
64 // outer + innerHash
\r
65 outerKey.position = hashKey.length;
\r
66 outerKey.writeBytes(innerHash);
\r
67 var outerHash:ByteArray = hash.hash(outerKey);
\r
68 if (bits>0 && bits<8*outerHash.length) {
\r
69 outerHash.length = bits/8;
\r
73 public function dispose():void {
\r
77 public function toString():String {
\r
78 return "hmac-"+(bits>0?bits+"-":"")+hash.toString();
\r