1: <?php
2:
3: /**
4: * Copyright 2015, Eduardo Trujillo
5: *
6: * For the full copyright and license information, please view the LICENSE
7: * file that was distributed with this source code.
8: *
9: * This file is part of the Nucleus package
10: */
11:
12: namespace Chromabits\Nucleus\Hashing;
13:
14: use Chromabits\Nucleus\Foundation\BaseObject;
15: use Chromabits\Nucleus\Meditation\Arguments;
16: use Chromabits\Nucleus\Meditation\Boa;
17:
18: /**
19: * Class HmacHasher.
20: *
21: * @author Eduardo Trujillo <ed@chromabits.com>
22: * @package Chromabits\Nucleus\Hashing
23: */
24: class HmacHasher extends BaseObject
25: {
26: /**
27: * Algorithm to use for hashing.
28: *
29: * @var string
30: */
31: protected $algorithm;
32:
33: /**
34: * Construct a new instance of a HmacHasher.
35: *
36: * @param string $algorithm
37: */
38: public function __construct($algorithm = 'sha512')
39: {
40: parent::__construct();
41:
42: $this->algorithm = $algorithm;
43: }
44:
45: /**
46: * Get a list of supported hashing algorithms.
47: *
48: * @return array
49: */
50: public static function getAlgorithms()
51: {
52: return hash_algos();
53: }
54:
55: /**
56: * Generate a hash of the content using the provided private key.
57: *
58: * @param string $content
59: * @param string $privateKey
60: *
61: * @return string
62: */
63: public function hash($content, $privateKey)
64: {
65: Arguments::define(Boa::string(), Boa::string())
66: ->check($content, $privateKey);
67:
68: return hash_hmac($this->algorithm, $content, $privateKey);
69: }
70:
71: /**
72: * Verify that a hash is valid.
73: *
74: * @param string $hash
75: * @param string $content
76: * @param string $privateKey
77: *
78: * @return bool
79: */
80: public function verify($hash, $content, $privateKey)
81: {
82: return $this->hash($content, $privateKey) === $hash;
83: }
84: }
85: