cryptal  latest
Cryptography Abstraction Layer
Mac.php
1 <?php
2 
4 
10 
11 class Mac extends \php_user_filter
12 {
13  protected $context;
14 
15  public function onCreate()
16  {
17  if (!isset($this->params['algorithm']) ||
18  !is_object($this->params['algorithm']) ||
19  !($this->params['algorithm'] instanceof MacEnum)) {
20  throw new \InvalidArgumentException('Invalid algorithm');
21  }
22 
23  if (!isset($this->params['innerAlgorithm']) ||
24  !is_object($this->params['innerAlgorithm']) ||
25  !($this->params['innerAlgorithm'] instanceof SubAlgorithmAbstractEnum)) {
26  throw new \InvalidArgumentException('Invalid inner algorithm');
27  }
28 
29  if (!isset($this->params['key']) || !is_string($this->params['key'])) {
30  throw new \InvalidArgumentException('Missing or invalid key');
31  }
32 
33  $nonce = isset($this->params['nonce']) ? $this->params['nonce'] : '';
34  if (!is_string($nonce)) {
35  throw new \InvalidArgumentException('Invalid nonce');
36  }
37 
38  $allowUnsafe = isset($this->params['allowUnsafe']) ? (bool) $this->params['allowUnsafe'] : false;
39  $this->context = Registry::buildMac(
40  $this->params['algorithm'],
41  $this->params['innerAlgorithm'],
42  $this->params['key'],
43  $nonce,
44  $allowUnsafe
45  );
46  return true;
47  }
48 
49  public function filter($in, $out, &$consumed, $closing)
50  {
51  while ($bucket = stream_bucket_make_writeable($in)) {
52  $this->context->update($bucket->data);
53  $consumed += $bucket->datalen;
54  }
55 
56  if ($closing) {
57  $bucket = stream_bucket_new($this->stream, $this->context->finalize(true));
58  stream_bucket_append($out, $bucket);
59  }
60 
61  return PSFS_PASS_ON;
62  }
63 }