Commit | Line | Data |
---|---|---|
14d4f286 S |
1 | <?php |
2 | /** | |
3 | * The CTR (Counter) mode implementation | |
4 | * | |
5 | * PHP version 5.3 | |
6 | * | |
7 | * @category PHPCryptLib | |
8 | * @package Cipher | |
9 | * @subpackage Block | |
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@@ | |
14 | */ | |
15 | ||
16 | namespace CryptLib\Cipher\Block\Mode; | |
17 | ||
18 | use CryptLib\Core\BaseConverter; | |
19 | use CryptLib\Core\BigMath; | |
20 | ||
21 | /** | |
22 | * The CTR (Counter) mode implementation | |
23 | * | |
24 | * @category PHPCryptLib | |
25 | * @package Cipher | |
26 | * @subpackage Block | |
27 | * @author Anthony Ferrara <ircmaxell@ircmaxell.com> | |
28 | */ | |
29 | ||
30 | class CTR extends \CryptLib\Cipher\Block\AbstractMode { | |
31 | ||
32 | /** | |
33 | * @var BigMath An instance of the BigMath library | |
34 | */ | |
35 | protected $bigMath = null; | |
36 | ||
37 | /** | |
38 | * Build the instance of the cipher mode | |
39 | * | |
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 | |
43 | */ | |
44 | public function __construct( | |
45 | \CryptLib\Cipher\Block\Cipher $cipher, | |
46 | $initv, | |
47 | array $options = array() | |
48 | ) { | |
49 | parent::__construct($cipher, $initv, $options); | |
50 | $this->bigMath = BigMath::createFromServerConfiguration(); | |
51 | } | |
52 | ||
53 | /** | |
54 | * Reset the mode to start over (destroying any intermediate state) | |
55 | * | |
56 | * @return void | |
57 | */ | |
58 | public function reset() { | |
59 | $this->state = BaseConverter::ConvertFromBinary($this->initv, '0123456789'); | |
60 | $this->state = ltrim($this->state, '0'); | |
61 | } | |
62 | ||
63 | /** | |
64 | * Decrypt the data using the supplied key, cipher | |
65 | * | |
66 | * @param string $data The data to decrypt | |
67 | * | |
68 | * @return string The decrypted data | |
69 | */ | |
70 | protected function decryptBlock($data) { | |
71 | return $this->encryptBlock($data); | |
72 | } | |
73 | ||
74 | /** | |
75 | * Encrypt the data using the supplied key, cipher | |
76 | * | |
77 | * @param string $data The data to encrypt | |
78 | * | |
79 | * @return string The encrypted data | |
80 | */ | |
81 | protected function encryptBlock($data) { | |
82 | $size = $this->cipher->getBlockSize(); | |
83 | $state = str_pad( | |
84 | BaseConverter::convertToBinary($this->state, '0123456789'), | |
85 | $size, | |
86 | chr(0), | |
87 | STR_PAD_LEFT | |
88 | ); | |
89 | $stub = $this->cipher->encryptBlock($state); | |
90 | $this->state = $this->bigMath->add($this->state, 1); | |
91 | return $stub ^ $data; | |
92 | } | |
93 | ||
94 | } |