3 * The CTR (Counter) mode implementation
7 * @category PHPCryptLib
10 * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
11 * @copyright 2011 The Authors
12 * @license http://www.opensource.org/licenses/mit-license.html MIT License
13 * @version Build @@version@@
16 namespace CryptLib\Cipher\Block\Mode
;
18 use CryptLib\Core\BaseConverter
;
19 use CryptLib\Core\BigMath
;
22 * The CTR (Counter) mode implementation
24 * @category PHPCryptLib
27 * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
30 class CTR
extends \CryptLib\Cipher\Block\AbstractMode
{
33 * @var BigMath An instance of the BigMath library
35 protected $bigMath = null;
38 * Build the instance of the cipher mode
40 * @param Cipher $cipher The cipher to use for encryption/decryption
41 * @param string $initv The initialization vector (empty if not needed)
42 * @param array $options An array of mode-specific options
44 public function __construct(
45 \CryptLib\Cipher\Block\Cipher
$cipher,
47 array $options = array()
49 parent
::__construct($cipher, $initv, $options);
50 $this->bigMath
= BigMath
::createFromServerConfiguration();
54 * Reset the mode to start over (destroying any intermediate state)
58 public function reset() {
59 $this->state
= BaseConverter
::ConvertFromBinary($this->initv
, '0123456789');
60 $this->state
= ltrim($this->state
, '0');
64 * Decrypt the data using the supplied key, cipher
66 * @param string $data The data to decrypt
68 * @return string The decrypted data
70 protected function decryptBlock($data) {
71 return $this->encryptBlock($data);
75 * Encrypt the data using the supplied key, cipher
77 * @param string $data The data to encrypt
79 * @return string The encrypted data
81 protected function encryptBlock($data) {
82 $size = $this->cipher
->getBlockSize();
84 BaseConverter
::convertToBinary($this->state
, '0123456789'),
89 $stub = $this->cipher
->encryptBlock($state);
90 $this->state
= $this->bigMath
->add($this->state
, 1);