Elgg  Version 6.2
HmacFactory.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Security;
4 
5 use Elgg\Traits\TimeUsing;
6 
10 class HmacFactory {
11 
12  use TimeUsing;
13 
20  public function __construct(protected SiteSecret $site_secret, protected Crypto $crypto) {
21  }
22 
32  public function getHmac($data, $algo = 'sha256', $key = '') {
33  if (!$key) {
34  $key = $this->site_secret->get(true);
35  }
36 
37  return new Hmac($key, [$this->crypto, 'areEqual'], $data, $algo);
38  }
39 
49  public function generateInviteCode(string $username): string {
50  $time = $this->getCurrentTime()->getTimestamp();
51  $token = $this->getHmac([$time, $username])->getToken();
52 
53  return "{$time}.{$token}";
54  }
55 
66  public function validateInviteCode(string $username, string $code): bool {
67  // validate the format of the token created by self::generateInviteCode()
68  $matches = [];
69  if (!preg_match('~^(\d+)\.([a-zA-Z0-9\-_]+)$~', $code, $matches)) {
70  return false;
71  }
72 
73  $time = (int) $matches[1];
74  $mac = $matches[2];
75 
76  return $this->getHmac([$time, $username])->matchesToken($mac);
77  }
78 }
$username
Definition: delete.php:23
if(! $annotation instanceof ElggAnnotation) $time
Definition: time.php:20
if(! $entity instanceof \ElggUser) $data
Definition: attributes.php:13
Cryptographic services.
Definition: Crypto.php:12
Provides a factory for HMAC objects.
Definition: HmacFactory.php:10
validateInviteCode(string $username, string $code)
Validate a user's invite code.
Definition: HmacFactory.php:66
generateInviteCode(string $username)
Generates a unique invite code for a user.
Definition: HmacFactory.php:49
__construct(protected SiteSecret $site_secret, protected Crypto $crypto)
Constructor.
Definition: HmacFactory.php:20
getHmac($data, $algo='sha256', $key='')
Get an HMAC token builder/validator object.
Definition: HmacFactory.php:32
Component for creating HMAC tokens.
Definition: Hmac.php:10
Manages a site-specific secret key, encoded as a 32 byte string "secret".
Definition: SiteSecret.php:24
$mac
Definition: contents.php:14
if($container instanceof ElggGroup && $container->guid !=elgg_get_page_owner_guid()) $key
Definition: summary.php:44
$token
$site_secret
Definition: site_secret.php:13