Elgg  Version 5.1
Hmac.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Security;
4 
6 
10 class Hmac {
11 
15  private $key;
16 
20  private $comparator;
21 
25  private $data;
26 
30  private $algo;
31 
42  public function __construct($key, callable $comparator, $data, $algo = 'sha256') {
43  $this->key = $key;
44  $this->comparator = $comparator;
45  if (!$data) {
46  throw new InvalidArgumentException('$data cannot be empty');
47  }
48 
49  if (!is_string($data)) {
50  $data = serialize($data);
51  }
52 
53  $this->data = $data;
54  $this->algo = $algo;
55  }
56 
62  public function getToken() {
63  $bytes = hash_hmac($this->algo, $this->data, $this->key, true);
64  return Base64Url::encode($bytes);
65  }
66 
73  public function matchesToken($token) {
74  $expected_token = $this->getToken();
75  return call_user_func($this->comparator, $expected_token, $token);
76  }
77 }
Exception thrown if an argument is not of the expected type.
matchesToken($token)
Does the MAC match the given token?
Definition: Hmac.php:73
getToken()
Get the HMAC token in Base64URL encoding.
Definition: Hmac.php:62
Component for creating HMAC tokens.
Definition: Hmac.php:10
$token
static encode($bytes)
Encode base 64 URL.
Definition: Base64Url.php:18
__construct($key, callable $comparator, $data, $algo= 'sha256')
Constructor.
Definition: Hmac.php:42