Debian Codegraph @

lib/3rdParty/composer/web-auth/cose-lib/src/Algorithm/Mac/Hmac.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Cose\Algorithm\Mac;
6
7 use Cose\Key\Key;
8 use Cose\Key\SymmetricKey;
9 use InvalidArgumentException;
10
11 /**
12 * @see \Cose\Tests\Algorithm\Mac\HmacTest
13 */
14 abstract class Hmac implements Mac
15 {
16 public function hash(string $data, Key $key): string
17 {
18 $this->checKey($key);
19 $signature = hash_hmac($this->getHashAlgorithm(), $data, (string) $key->get(SymmetricKey::DATA_K), true);
20
21 return substr($signature, 0, intdiv($this->getSignatureLength(), 8));
22 }
23
24 public function verify(string $data, Key $key, string $signature): bool
25 {
26 return hash_equals($this->hash($data, $key), $signature);
27 }
28
29 abstract protected function getHashAlgorithm(): string;
30
31 abstract protected function getSignatureLength(): int;
32
33 private function checKey(Key $key): void
34 {
35 if ($key->type() !== Key::TYPE_OCT && $key->type() !== Key::TYPE_NAME_OCT) {
36 throw new InvalidArgumentException('Invalid key. Must be of type symmetric');
37 }
38
39 if (! $key->has(SymmetricKey::DATA_K)) {
40 throw new InvalidArgumentException('Invalid key. The value of the key is missing');
41 }
42 }
43 }