cryptal  latest
Cryptography Abstraction Layer
EAX.php
1 <?php
2 
4 
9 
13 class EAX implements AsymmetricModeInterface
14 {
16  protected $cipher;
17 
19  protected $nonce;
20 
22  protected $taglen;
23 
24  public function __construct(CryptoInterface $cipher, $iv, $tagLength)
25  {
26  $this->cipher = $cipher;
27  $this->nonce = $iv;
28  $this->taglen = $tagLength;
29  $this->omac = new Cmac(MacEnum::MAC_CMAC(), $cipher->getCipher(), $cipher->getKey());
30  }
31 
32  public function encrypt($data, $context)
33  {
34  $options = stream_context_get_options($context);
35  $H = isset($options['cryptal']['data']) ? (string) $options['cryptal']['data'] : '';
36  $blockSize = $this->cipher->getBlockSize();
37  $pad = str_repeat("\x00", $blockSize - 1);
38 
39  $omac = clone $this->omac;
40  $tN = $omac->update($pad . "\x00" . $this->nonce)->finalize(true);
41  $omac = clone $this->omac;
42  $tH = $omac->update($pad . "\x01" . $H)->finalize(true);
43 
44  $ctr = new CTR($this->cipher, $tN, $this->taglen);
45  $C = '';
46  foreach (str_split($data, $blockSize) as $block) {
47  $C .= $ctr->encrypt($block, null);
48  }
49 
50  $omac = clone $this->omac;
51  $tC = $omac->update($pad . "\x02" . $C)->finalize(true);
52  stream_context_set_option($context, 'cryptal', 'tag', (string) substr($tN ^ $tH ^ $tC, 0, $this->taglen));
53  return $C;
54  }
55 
56  public function decrypt($data, $context)
57  {
58  $options = stream_context_get_options($context);
59  $H = isset($options['cryptal']['data']) ? (string) $options['cryptal']['data'] : '';
60  $T = isset($options['cryptal']['tag']) ? (string) $options['cryptal']['tag'] : '';
61  $blockSize = $this->cipher->getBlockSize();
62  $pad = str_repeat("\x00", $blockSize - 1);
63 
64  $omac = clone $this->omac;
65  $tN = $omac->update($pad . "\x00" . $this->nonce)->finalize(true);
66  $omac = clone $this->omac;
67  $tH = $omac->update($pad . "\x01" . $H)->finalize(true);
68  $omac = clone $this->omac;
69  $tC = $omac->update($pad . "\x02" . $data)->finalize(true);
70  $T2 = (string) substr($tN ^ $tH ^ $tC, 0, $this->taglen);
71 
72  if ($T2 !== $T) {
73  throw new \InvalidArgumentException('Tag does not match expected value');
74  }
75 
76  $ctr = new CTR($this->cipher, $tN, $this->taglen);
77  $P = '';
78  foreach (str_split($data, $blockSize) as $block) {
79  $P .= $ctr->encrypt($block, null);
80  }
81 
82  return $P;
83  }
84 }
$taglen
Output tag length.
Definition: EAX.php:22
encrypt($data, $context)
Definition: EAX.php:32
__construct(CryptoInterface $cipher, $iv, $tagLength)
Definition: EAX.php:24
decrypt($data, $context)
Definition: EAX.php:56