Elgg  Version master
Hmac.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Security;
4 
6 
10 class Hmac {
11 
15  protected $comparator;
16 
17  protected string $data;
18 
29  public function __construct(protected string $key, callable $comparator, $data, protected string $algo = 'sha256') {
30  $this->comparator = $comparator;
31  if (!$data) {
32  throw new InvalidArgumentException('$data cannot be empty');
33  }
34 
35  if (!is_string($data)) {
36  $data = serialize($data);
37  }
38 
39  $this->data = $data;
40  }
41 
47  public function getToken(): string {
48  $bytes = hash_hmac($this->algo, $this->data, $this->key, true);
49  return Base64Url::encode($bytes);
50  }
51 
59  public function matchesToken($token): bool {
60  $expected_token = $this->getToken();
61  return call_user_func($this->comparator, $expected_token, $token);
62  }
63 }
Exception thrown if an argument is not of the expected type.
__construct(protected string $key, callable $comparator, $data, protected string $algo= 'sha256')
Constructor.
Definition: Hmac.php:29
matchesToken($token)
Does the MAC match the given token?
Definition: Hmac.php:59
string $data
Definition: Hmac.php:17
getToken()
Get the HMAC token in Base64URL encoding.
Definition: Hmac.php:47
Component for creating HMAC tokens.
Definition: Hmac.php:10
$token
if($container instanceof ElggGroup &&$container->guid!=elgg_get_page_owner_guid()) $key
Definition: summary.php:44
static encode($bytes)
Encode base 64 URL.
Definition: Base64Url.php:18