Commit | Line | Data |
---|---|---|
14d4f286 S |
1 | <?php |
2 | /** | |
3 | * A Hash-Base MAC generator | |
4 | * | |
5 | * PHP version 5.3 | |
6 | * | |
7 | * @category PHPCryptLib | |
8 | * @package MAC | |
9 | * @subpackage Implementation | |
10 | * @author Anthony Ferrara <ircmaxell@ircmaxell.com> | |
11 | * @copyright 2011 The Authors | |
12 | * @license http://www.opensource.org/licenses/mit-license.html MIT License | |
13 | * @version Build @@version@@ | |
14 | */ | |
15 | namespace CryptLib\MAC\Implementation; | |
16 | ||
17 | use \CryptLib\Hash\Hash; | |
18 | ||
19 | /** | |
20 | * A Hash-Base MAC generator | |
21 | * | |
22 | * @category PHPCryptLib | |
23 | * @package MAC | |
24 | * @subpackage Implementation | |
25 | */ | |
26 | class HMAC extends \CryptLib\MAC\AbstractMAC { | |
27 | ||
28 | /** | |
29 | * @var array The stored options for this instance | |
30 | */ | |
31 | protected $options = array( | |
32 | 'hash' => 'sha256', | |
33 | ); | |
34 | ||
35 | /** | |
36 | * Generate the MAC using the supplied data | |
37 | * | |
38 | * @param string $data The data to use to generate the MAC with | |
39 | * @param string $key The key to generate the MAC | |
40 | * @param int $size The size of the output to return | |
41 | * | |
42 | * @return string The generated MAC of the appropriate size | |
43 | */ | |
44 | public function generate($data, $key, $size = 0) { | |
45 | $hash = $this->options['hash']; | |
46 | $outputSize = Hash::getHashSize($hash); | |
47 | if ($size == 0) { | |
48 | $size = $outputSize; | |
49 | } | |
50 | if ($size > $outputSize) { | |
51 | throw new \OutOfRangeException( | |
52 | sprintf( | |
53 | 'The size is too big for the hash primitive [%d:%d]', | |
54 | $size, | |
55 | $outputSize | |
56 | ) | |
57 | ); | |
58 | } | |
59 | $return = hash_hmac($hash, $data, $key, true); | |
60 | return substr($return, 0, $size); | |
61 | } | |
62 | ||
63 | } |