cryptal  latest
Cryptography Abstraction Layer
CTR.php
1 <?php
2 
4 
7 
11 class CTR implements SymmetricModeInterface
12 {
14  protected $cipher;
15 
17  protected $counter;
18 
20  protected $blockSize;
21 
22  public function __construct(CryptoInterface $cipher, $iv, $tagLength)
23  {
24  $ivSize = strlen($iv);
25  $blockSize = $cipher->getBlockSize();
26  if ($ivSize !== $blockSize) {
27  throw new \Exception("Invalid IV size (got $ivSize bytes; should be $blockSize)");
28  }
29 
30  $this->cipher = $cipher;
31  $this->counter = $iv;
32  $this->blockSize = $blockSize;
33  }
34 
36  protected function incrementCounter()
37  {
38  $carry = 1;
39  for ($i = $this->blockSize - 1; $i >= 0; $i--) {
40  // chr() takes care of overflows automatically.
41  $this->counter[$i] = chr(ord($this->counter[$i]) + $carry);
42  $carry &= ("\x00" === $this->counter[$i]);
43  }
44  }
45 
46  public function encrypt($data, $context)
47  {
48  $res = $this->cipher->encrypt('', $this->counter);
49  $this->incrementCounter();
50  return $res ^ $data;
51  }
52 }
$blockSize
Cipher block size.
Definition: CTR.php:20
__construct(CryptoInterface $cipher, $iv, $tagLength)
Definition: CTR.php:22
encrypt($data, $context)
Definition: CTR.php:46
incrementCounter()
Increment the value of the counter by one.
Definition: CTR.php:36