PageRenderTime 66ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/updraftplus/includes/phpseclib/Crypt/Base.php

https://github.com/tjworks/mongoing
PHP | 1989 lines | 1103 code | 97 blank | 789 comment | 120 complexity | 8414fe454de0aa9bb687d7be5ebc1a1d MD5 | raw file
Possible License(s): GPL-2.0, GPL-3.0, Apache-2.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Base Class for all Crypt_* cipher classes
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * Internally for phpseclib developers:
  9. * If you plan to add a new cipher class, please note following rules:
  10. *
  11. * - The new Crypt_* cipher class should extend Crypt_Base
  12. *
  13. * - Following methods are then required to be overridden/overloaded:
  14. *
  15. * - _encryptBlock()
  16. *
  17. * - _decryptBlock()
  18. *
  19. * - _setupKey()
  20. *
  21. * - All other methods are optional to be overridden/overloaded
  22. *
  23. * - Look at the source code of the current ciphers how they extend Crypt_Base
  24. * and take one of them as a start up for the new cipher class.
  25. *
  26. * - Please read all the other comments/notes/hints here also for each class var/method
  27. *
  28. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  29. * of this software and associated documentation files (the "Software"), to deal
  30. * in the Software without restriction, including without limitation the rights
  31. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  32. * copies of the Software, and to permit persons to whom the Software is
  33. * furnished to do so, subject to the following conditions:
  34. *
  35. * The above copyright notice and this permission notice shall be included in
  36. * all copies or substantial portions of the Software.
  37. *
  38. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  39. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  42. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  43. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  44. * THE SOFTWARE.
  45. *
  46. * @category Crypt
  47. * @package Crypt_Base
  48. * @author Jim Wigginton <terrafrost@php.net>
  49. * @author Hans-Juergen Petrich <petrich@tronic-media.com>
  50. * @copyright MMVII Jim Wigginton
  51. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  52. * @version 1.0.1
  53. * @link http://phpseclib.sourceforge.net
  54. */
  55. /**#@+
  56. * @access public
  57. * @see Crypt_Base::encrypt()
  58. * @see Crypt_Base::decrypt()
  59. */
  60. /**
  61. * Encrypt / decrypt using the Counter mode.
  62. *
  63. * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
  64. *
  65. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
  66. */
  67. define('CRYPT_MODE_CTR', -1);
  68. /**
  69. * Encrypt / decrypt using the Electronic Code Book mode.
  70. *
  71. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
  72. */
  73. define('CRYPT_MODE_ECB', 1);
  74. /**
  75. * Encrypt / decrypt using the Code Book Chaining mode.
  76. *
  77. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
  78. */
  79. define('CRYPT_MODE_CBC', 2);
  80. /**
  81. * Encrypt / decrypt using the Cipher Feedback mode.
  82. *
  83. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
  84. */
  85. define('CRYPT_MODE_CFB', 3);
  86. /**
  87. * Encrypt / decrypt using the Output Feedback mode.
  88. *
  89. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
  90. */
  91. define('CRYPT_MODE_OFB', 4);
  92. /**
  93. * Encrypt / decrypt using streaming mode.
  94. *
  95. */
  96. define('CRYPT_MODE_STREAM', 5);
  97. /**#@-*/
  98. /**#@+
  99. * @access private
  100. * @see Crypt_Base::Crypt_Base()
  101. */
  102. /**
  103. * Base value for the internal implementation $engine switch
  104. */
  105. define('CRYPT_MODE_INTERNAL', 1);
  106. /**
  107. * Base value for the mcrypt implementation $engine switch
  108. */
  109. define('CRYPT_MODE_MCRYPT', 2);
  110. /**#@-*/
  111. /**
  112. * Base Class for all Crypt_* cipher classes
  113. *
  114. * @author Jim Wigginton <terrafrost@php.net>
  115. * @author Hans-Juergen Petrich <petrich@tronic-media.com>
  116. * @version 1.0.0
  117. * @access public
  118. * @package Crypt_Base
  119. */
  120. class Crypt_Base {
  121. /**
  122. * The Encryption Mode
  123. *
  124. * @see Crypt_Base::Crypt_Base()
  125. * @var Integer
  126. * @access private
  127. */
  128. var $mode;
  129. /**
  130. * The Block Length of the block cipher
  131. *
  132. * @var Integer
  133. * @access private
  134. */
  135. var $block_size = 16;
  136. /**
  137. * The Key
  138. *
  139. * @see Crypt_Base::setKey()
  140. * @var String
  141. * @access private
  142. */
  143. var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
  144. /**
  145. * The Initialization Vector
  146. *
  147. * @see Crypt_Base::setIV()
  148. * @var String
  149. * @access private
  150. */
  151. var $iv;
  152. /**
  153. * A "sliding" Initialization Vector
  154. *
  155. * @see Crypt_Base::enableContinuousBuffer()
  156. * @see Crypt_Base::_clearBuffers()
  157. * @var String
  158. * @access private
  159. */
  160. var $encryptIV;
  161. /**
  162. * A "sliding" Initialization Vector
  163. *
  164. * @see Crypt_Base::enableContinuousBuffer()
  165. * @see Crypt_Base::_clearBuffers()
  166. * @var String
  167. * @access private
  168. */
  169. var $decryptIV;
  170. /**
  171. * Continuous Buffer status
  172. *
  173. * @see Crypt_Base::enableContinuousBuffer()
  174. * @var Boolean
  175. * @access private
  176. */
  177. var $continuousBuffer = false;
  178. /**
  179. * Encryption buffer for CTR, OFB and CFB modes
  180. *
  181. * @see Crypt_Base::encrypt()
  182. * @see Crypt_Base::_clearBuffers()
  183. * @var Array
  184. * @access private
  185. */
  186. var $enbuffer;
  187. /**
  188. * Decryption buffer for CTR, OFB and CFB modes
  189. *
  190. * @see Crypt_Base::decrypt()
  191. * @see Crypt_Base::_clearBuffers()
  192. * @var Array
  193. * @access private
  194. */
  195. var $debuffer;
  196. /**
  197. * mcrypt resource for encryption
  198. *
  199. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  200. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  201. *
  202. * @see Crypt_Base::encrypt()
  203. * @var Resource
  204. * @access private
  205. */
  206. var $enmcrypt;
  207. /**
  208. * mcrypt resource for decryption
  209. *
  210. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  211. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  212. *
  213. * @see Crypt_Base::decrypt()
  214. * @var Resource
  215. * @access private
  216. */
  217. var $demcrypt;
  218. /**
  219. * Does the enmcrypt resource need to be (re)initialized?
  220. *
  221. * @see Crypt_Twofish::setKey()
  222. * @see Crypt_Twofish::setIV()
  223. * @var Boolean
  224. * @access private
  225. */
  226. var $enchanged = true;
  227. /**
  228. * Does the demcrypt resource need to be (re)initialized?
  229. *
  230. * @see Crypt_Twofish::setKey()
  231. * @see Crypt_Twofish::setIV()
  232. * @var Boolean
  233. * @access private
  234. */
  235. var $dechanged = true;
  236. /**
  237. * mcrypt resource for CFB mode
  238. *
  239. * mcrypt's CFB mode, in (and only in) buffered context,
  240. * is broken, so phpseclib implements the CFB mode by it self,
  241. * even when the mcrypt php extension is available.
  242. *
  243. * In order to do the CFB-mode work (fast) phpseclib
  244. * use a separate ECB-mode mcrypt resource.
  245. *
  246. * @link http://phpseclib.sourceforge.net/cfb-demo.phps
  247. * @see Crypt_Base::encrypt()
  248. * @see Crypt_Base::decrypt()
  249. * @see Crypt_Base::_setupMcrypt()
  250. * @var Resource
  251. * @access private
  252. */
  253. var $ecb;
  254. /**
  255. * Optimizing value while CFB-encrypting
  256. *
  257. * Only relevant if $continuousBuffer enabled
  258. * and $engine == CRYPT_MODE_MCRYPT
  259. *
  260. * It's faster to re-init $enmcrypt if
  261. * $buffer bytes > $cfb_init_len than
  262. * using the $ecb resource furthermore.
  263. *
  264. * This value depends of the choosen cipher
  265. * and the time it would be needed for it's
  266. * initialization [by mcrypt_generic_init()]
  267. * which, typically, depends on the complexity
  268. * on its internaly Key-expanding algorithm.
  269. *
  270. * @see Crypt_Base::encrypt()
  271. * @var Integer
  272. * @access private
  273. */
  274. var $cfb_init_len = 600;
  275. /**
  276. * Does internal cipher state need to be (re)initialized?
  277. *
  278. * @see setKey()
  279. * @see setIV()
  280. * @see disableContinuousBuffer()
  281. * @var Boolean
  282. * @access private
  283. */
  284. var $changed = true;
  285. /**
  286. * Padding status
  287. *
  288. * @see Crypt_Base::enablePadding()
  289. * @var Boolean
  290. * @access private
  291. */
  292. var $padding = true;
  293. /**
  294. * Is the mode one that is paddable?
  295. *
  296. * @see Crypt_Base::Crypt_Base()
  297. * @var Boolean
  298. * @access private
  299. */
  300. var $paddable = false;
  301. /**
  302. * Holds which crypt engine internaly should be use,
  303. * which will be determined automatically on __construct()
  304. *
  305. * Currently available $engines are:
  306. * - CRYPT_MODE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required)
  307. * - CRYPT_MODE_INTERNAL (slower, pure php-engine, no php-extension required)
  308. *
  309. * In the pipeline... maybe. But currently not available:
  310. * - CRYPT_MODE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required)
  311. *
  312. * If possible, CRYPT_MODE_MCRYPT will be used for each cipher.
  313. * Otherwise CRYPT_MODE_INTERNAL
  314. *
  315. * @see Crypt_Base::encrypt()
  316. * @see Crypt_Base::decrypt()
  317. * @var Integer
  318. * @access private
  319. */
  320. var $engine;
  321. /**
  322. * The mcrypt specific name of the cipher
  323. *
  324. * Only used if $engine == CRYPT_MODE_MCRYPT
  325. *
  326. * @link http://www.php.net/mcrypt_module_open
  327. * @link http://www.php.net/mcrypt_list_algorithms
  328. * @see Crypt_Base::_setupMcrypt()
  329. * @var String
  330. * @access private
  331. */
  332. var $cipher_name_mcrypt;
  333. /**
  334. * The default password key_size used by setPassword()
  335. *
  336. * @see Crypt_Base::setPassword()
  337. * @var Integer
  338. * @access private
  339. */
  340. var $password_key_size = 32;
  341. /**
  342. * The default salt used by setPassword()
  343. *
  344. * @see Crypt_Base::setPassword()
  345. * @var String
  346. * @access private
  347. */
  348. var $password_default_salt = 'phpseclib/salt';
  349. /**
  350. * The namespace used by the cipher for its constants.
  351. *
  352. * ie: AES.php is using CRYPT_AES_MODE_* for its constants
  353. * so $const_namespace is AES
  354. *
  355. * DES.php is using CRYPT_DES_MODE_* for its constants
  356. * so $const_namespace is DES... and so on
  357. *
  358. * All CRYPT_<$const_namespace>_MODE_* are aliases of
  359. * the generic CRYPT_MODE_* constants, so both could be used
  360. * for each cipher.
  361. *
  362. * Example:
  363. * $aes = new Crypt_AES(CRYPT_AES_MODE_CFB); // $aes will operate in cfb mode
  364. * $aes = new Crypt_AES(CRYPT_MODE_CFB); // identical
  365. *
  366. * @see Crypt_Base::Crypt_Base()
  367. * @var String
  368. * @access private
  369. */
  370. var $const_namespace;
  371. /**
  372. * The name of the performance-optimized callback function
  373. *
  374. * Used by encrypt() / decrypt()
  375. * only if $engine == CRYPT_MODE_INTERNAL
  376. *
  377. * @see Crypt_Base::encrypt()
  378. * @see Crypt_Base::decrypt()
  379. * @see Crypt_Base::_setupInlineCrypt()
  380. * @see Crypt_Base::$use_inline_crypt
  381. * @var Callback
  382. * @access private
  383. */
  384. var $inline_crypt;
  385. /**
  386. * Holds whether performance-optimized $inline_crypt() can/should be used.
  387. *
  388. * @see Crypt_Base::encrypt()
  389. * @see Crypt_Base::decrypt()
  390. * @see Crypt_Base::inline_crypt
  391. * @var mixed
  392. * @access private
  393. */
  394. var $use_inline_crypt;
  395. /**
  396. * Default Constructor.
  397. *
  398. * Determines whether or not the mcrypt extension should be used.
  399. *
  400. * $mode could be:
  401. *
  402. * - CRYPT_MODE_ECB
  403. *
  404. * - CRYPT_MODE_CBC
  405. *
  406. * - CRYPT_MODE_CTR
  407. *
  408. * - CRYPT_MODE_CFB
  409. *
  410. * - CRYPT_MODE_OFB
  411. *
  412. * (or the alias constants of the choosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...)
  413. *
  414. * If not explictly set, CRYPT_MODE_CBC will be used.
  415. *
  416. * @param optional Integer $mode
  417. * @access public
  418. */
  419. function Crypt_Base($mode = CRYPT_MODE_CBC)
  420. {
  421. $const_crypt_mode = 'CRYPT_' . $this->const_namespace . '_MODE';
  422. // Determining the availibility of mcrypt support for the cipher
  423. if (!defined($const_crypt_mode)) {
  424. switch (true) {
  425. case extension_loaded('mcrypt') && in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms()):
  426. define($const_crypt_mode, CRYPT_MODE_MCRYPT);
  427. break;
  428. default:
  429. define($const_crypt_mode, CRYPT_MODE_INTERNAL);
  430. }
  431. }
  432. // Determining which internal $engine should be used.
  433. // The fastes possible first.
  434. switch (true) {
  435. case empty($this->cipher_name_mcrypt): // The cipher module has no mcrypt-engine support at all so we force CRYPT_MODE_INTERNAL
  436. $this->engine = CRYPT_MODE_INTERNAL;
  437. break;
  438. case constant($const_crypt_mode) == CRYPT_MODE_MCRYPT:
  439. $this->engine = CRYPT_MODE_MCRYPT;
  440. break;
  441. default:
  442. $this->engine = CRYPT_MODE_INTERNAL;
  443. }
  444. // $mode dependent settings
  445. switch ($mode) {
  446. case CRYPT_MODE_ECB:
  447. $this->paddable = true;
  448. $this->mode = $mode;
  449. break;
  450. case CRYPT_MODE_CTR:
  451. case CRYPT_MODE_CFB:
  452. case CRYPT_MODE_OFB:
  453. case CRYPT_MODE_STREAM:
  454. $this->mode = $mode;
  455. break;
  456. case CRYPT_MODE_CBC:
  457. default:
  458. $this->paddable = true;
  459. $this->mode = CRYPT_MODE_CBC;
  460. }
  461. // Determining whether inline crypting can be used by the cipher
  462. if ($this->use_inline_crypt !== false && function_exists('create_function')) {
  463. $this->use_inline_crypt = true;
  464. }
  465. }
  466. /**
  467. * Sets the initialization vector. (optional)
  468. *
  469. * SetIV is not required when CRYPT_MODE_ECB (or ie for AES: CRYPT_AES_MODE_ECB) is being used. If not explictly set, it'll be assumed
  470. * to be all zero's.
  471. *
  472. * Note: Could, but not must, extend by the child Crypt_* class
  473. *
  474. * @access public
  475. * @param String $iv
  476. */
  477. function setIV($iv)
  478. {
  479. if ($this->mode == CRYPT_MODE_ECB) {
  480. return;
  481. }
  482. $this->iv = $iv;
  483. $this->changed = true;
  484. }
  485. /**
  486. * Sets the key.
  487. *
  488. * The min/max length(s) of the key depends on the cipher which is used.
  489. * If the key not fits the length(s) of the cipher it will paded with null bytes
  490. * up to the closest valid key length. If the key is more than max length,
  491. * we trim the excess bits.
  492. *
  493. * If the key is not explicitly set, it'll be assumed to be all null bytes.
  494. *
  495. * Note: Could, but not must, extend by the child Crypt_* class
  496. *
  497. * @access public
  498. * @param String $key
  499. */
  500. function setKey($key)
  501. {
  502. $this->key = $key;
  503. $this->changed = true;
  504. }
  505. /**
  506. * Sets the password.
  507. *
  508. * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
  509. * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
  510. * $hash, $salt, $count, $dkLen
  511. *
  512. * Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php
  513. *
  514. * Note: Could, but not must, extend by the child Crypt_* class
  515. *
  516. * @see Crypt/Hash.php
  517. * @param String $password
  518. * @param optional String $method
  519. * @access public
  520. */
  521. function setPassword($password, $method = 'pbkdf2')
  522. {
  523. $key = '';
  524. switch ($method) {
  525. default: // 'pbkdf2'
  526. $func_args = func_get_args();
  527. // Hash function
  528. $hash = isset($func_args[2]) ? $func_args[2] : 'sha1';
  529. // WPA and WPA2 use the SSID as the salt
  530. $salt = isset($func_args[3]) ? $func_args[3] : $this->password_default_salt;
  531. // RFC2898#section-4.2 uses 1,000 iterations by default
  532. // WPA and WPA2 use 4,096.
  533. $count = isset($func_args[4]) ? $func_args[4] : 1000;
  534. // Keylength
  535. $dkLen = isset($func_args[5]) ? $func_args[5] : $this->password_key_size;
  536. // Determining if php[>=5.5.0]'s hash_pbkdf2() function avail- and useable
  537. switch (true) {
  538. case !function_exists('hash_pbkdf2'):
  539. case !function_exists('hash_algos'):
  540. case !in_array($hash, hash_algos()):
  541. if (!class_exists('Crypt_Hash')) {
  542. require_once('Crypt/Hash.php');
  543. }
  544. $i = 1;
  545. while (strlen($key) < $dkLen) {
  546. $hmac = new Crypt_Hash();
  547. $hmac->setHash($hash);
  548. $hmac->setKey($password);
  549. $f = $u = $hmac->hash($salt . pack('N', $i++));
  550. for ($j = 2; $j <= $count; ++$j) {
  551. $u = $hmac->hash($u);
  552. $f^= $u;
  553. }
  554. $key.= $f;
  555. }
  556. $key = substr($key, 0, $dkLen);
  557. break;
  558. default:
  559. $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true);
  560. }
  561. }
  562. $this->setKey($key);
  563. }
  564. /**
  565. * Encrypts a message.
  566. *
  567. * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher
  568. * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's
  569. * necessary are discussed in the following
  570. * URL:
  571. *
  572. * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
  573. *
  574. * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
  575. * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that
  576. * length.
  577. *
  578. * Note: Could, but not must, extend by the child Crypt_* class
  579. *
  580. * @see Crypt_Base::decrypt()
  581. * @access public
  582. * @param String $plaintext
  583. * @return String $cipertext
  584. */
  585. function encrypt($plaintext)
  586. {
  587. if ($this->engine == CRYPT_MODE_MCRYPT) {
  588. if ($this->changed) {
  589. $this->_setupMcrypt();
  590. $this->changed = false;
  591. }
  592. if ($this->enchanged) {
  593. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  594. $this->enchanged = false;
  595. }
  596. // re: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
  597. // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
  598. // rewritten CFB implementation the above outputs the same thing twice.
  599. if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
  600. $block_size = $this->block_size;
  601. $iv = &$this->encryptIV;
  602. $pos = &$this->enbuffer['pos'];
  603. $len = strlen($plaintext);
  604. $ciphertext = '';
  605. $i = 0;
  606. if ($pos) {
  607. $orig_pos = $pos;
  608. $max = $block_size - $pos;
  609. if ($len >= $max) {
  610. $i = $max;
  611. $len-= $max;
  612. $pos = 0;
  613. } else {
  614. $i = $len;
  615. $pos+= $len;
  616. $len = 0;
  617. }
  618. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  619. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  620. $this->enbuffer['enmcrypt_init'] = true;
  621. }
  622. if ($len >= $block_size) {
  623. if ($this->enbuffer['enmcrypt_init'] === false || $len > $this->cfb_init_len) {
  624. if ($this->enbuffer['enmcrypt_init'] === true) {
  625. mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
  626. $this->enbuffer['enmcrypt_init'] = false;
  627. }
  628. $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size));
  629. $iv = substr($ciphertext, -$block_size);
  630. $len%= $block_size;
  631. } else {
  632. while ($len >= $block_size) {
  633. $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size);
  634. $ciphertext.= $iv;
  635. $len-= $block_size;
  636. $i+= $block_size;
  637. }
  638. }
  639. }
  640. if ($len) {
  641. $iv = mcrypt_generic($this->ecb, $iv);
  642. $block = $iv ^ substr($plaintext, -$len);
  643. $iv = substr_replace($iv, $block, 0, $len);
  644. $ciphertext.= $block;
  645. $pos = $len;
  646. }
  647. return $ciphertext;
  648. }
  649. if ($this->paddable) {
  650. $plaintext = $this->_pad($plaintext);
  651. }
  652. $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
  653. if (!$this->continuousBuffer) {
  654. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  655. }
  656. return $ciphertext;
  657. }
  658. if ($this->changed) {
  659. $this->_setup();
  660. $this->changed = false;
  661. }
  662. if ($this->use_inline_crypt) {
  663. $inline = $this->inline_crypt;
  664. return $inline('encrypt', $this, $plaintext);
  665. }
  666. if ($this->paddable) {
  667. $plaintext = $this->_pad($plaintext);
  668. }
  669. $buffer = &$this->enbuffer;
  670. $block_size = $this->block_size;
  671. $ciphertext = '';
  672. switch ($this->mode) {
  673. case CRYPT_MODE_ECB:
  674. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  675. $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));
  676. }
  677. break;
  678. case CRYPT_MODE_CBC:
  679. $xor = $this->encryptIV;
  680. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  681. $block = substr($plaintext, $i, $block_size);
  682. $block = $this->_encryptBlock($block ^ $xor);
  683. $xor = $block;
  684. $ciphertext.= $block;
  685. }
  686. if ($this->continuousBuffer) {
  687. $this->encryptIV = $xor;
  688. }
  689. break;
  690. case CRYPT_MODE_CTR:
  691. $xor = $this->encryptIV;
  692. if (strlen($buffer['encrypted'])) {
  693. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  694. $block = substr($plaintext, $i, $block_size);
  695. if (strlen($block) > strlen($buffer['encrypted'])) {
  696. $buffer['encrypted'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
  697. }
  698. $key = $this->_stringShift($buffer['encrypted'], $block_size);
  699. $ciphertext.= $block ^ $key;
  700. }
  701. } else {
  702. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  703. $block = substr($plaintext, $i, $block_size);
  704. $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
  705. $ciphertext.= $block ^ $key;
  706. }
  707. }
  708. if ($this->continuousBuffer) {
  709. $this->encryptIV = $xor;
  710. if ($start = strlen($plaintext) % $block_size) {
  711. $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
  712. }
  713. }
  714. break;
  715. case CRYPT_MODE_CFB:
  716. // cfb loosely routines inspired by openssl's:
  717. // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1}
  718. if ($this->continuousBuffer) {
  719. $iv = &$this->encryptIV;
  720. $pos = &$buffer['pos'];
  721. } else {
  722. $iv = $this->encryptIV;
  723. $pos = 0;
  724. }
  725. $len = strlen($plaintext);
  726. $i = 0;
  727. if ($pos) {
  728. $orig_pos = $pos;
  729. $max = $block_size - $pos;
  730. if ($len >= $max) {
  731. $i = $max;
  732. $len-= $max;
  733. $pos = 0;
  734. } else {
  735. $i = $len;
  736. $pos+= $len;
  737. $len = 0;
  738. }
  739. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  740. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  741. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  742. }
  743. while ($len >= $block_size) {
  744. $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size);
  745. $ciphertext.= $iv;
  746. $len-= $block_size;
  747. $i+= $block_size;
  748. }
  749. if ($len) {
  750. $iv = $this->_encryptBlock($iv);
  751. $block = $iv ^ substr($plaintext, $i);
  752. $iv = substr_replace($iv, $block, 0, $len);
  753. $ciphertext.= $block;
  754. $pos = $len;
  755. }
  756. break;
  757. case CRYPT_MODE_OFB:
  758. $xor = $this->encryptIV;
  759. if (strlen($buffer['xor'])) {
  760. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  761. $block = substr($plaintext, $i, $block_size);
  762. if (strlen($block) > strlen($buffer['xor'])) {
  763. $xor = $this->_encryptBlock($xor);
  764. $buffer['xor'].= $xor;
  765. }
  766. $key = $this->_stringShift($buffer['xor'], $block_size);
  767. $ciphertext.= $block ^ $key;
  768. }
  769. } else {
  770. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  771. $xor = $this->_encryptBlock($xor);
  772. $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor;
  773. }
  774. $key = $xor;
  775. }
  776. if ($this->continuousBuffer) {
  777. $this->encryptIV = $xor;
  778. if ($start = strlen($plaintext) % $block_size) {
  779. $buffer['xor'] = substr($key, $start) . $buffer['xor'];
  780. }
  781. }
  782. break;
  783. case CRYPT_MODE_STREAM:
  784. $ciphertext = $this->_encryptBlock($plaintext);
  785. break;
  786. }
  787. return $ciphertext;
  788. }
  789. /**
  790. * Decrypts a message.
  791. *
  792. * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until
  793. * it is.
  794. *
  795. * Note: Could, but not must, extend by the child Crypt_* class
  796. *
  797. * @see Crypt_Base::encrypt()
  798. * @access public
  799. * @param String $ciphertext
  800. * @return String $plaintext
  801. */
  802. function decrypt($ciphertext)
  803. {
  804. if ($this->engine == CRYPT_MODE_MCRYPT) {
  805. $block_size = $this->block_size;
  806. if ($this->changed) {
  807. $this->_setupMcrypt();
  808. $this->changed = false;
  809. }
  810. if ($this->dechanged) {
  811. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  812. $this->dechanged = false;
  813. }
  814. if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
  815. $iv = &$this->decryptIV;
  816. $pos = &$this->debuffer['pos'];
  817. $len = strlen($ciphertext);
  818. $plaintext = '';
  819. $i = 0;
  820. if ($pos) {
  821. $orig_pos = $pos;
  822. $max = $block_size - $pos;
  823. if ($len >= $max) {
  824. $i = $max;
  825. $len-= $max;
  826. $pos = 0;
  827. } else {
  828. $i = $len;
  829. $pos+= $len;
  830. $len = 0;
  831. }
  832. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  833. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  834. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  835. }
  836. if ($len >= $block_size) {
  837. $cb = substr($ciphertext, $i, $len - $len % $block_size);
  838. $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
  839. $iv = substr($cb, -$block_size);
  840. $len%= $block_size;
  841. }
  842. if ($len) {
  843. $iv = mcrypt_generic($this->ecb, $iv);
  844. $plaintext.= $iv ^ substr($ciphertext, -$len);
  845. $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
  846. $pos = $len;
  847. }
  848. return $plaintext;
  849. }
  850. if ($this->paddable) {
  851. // we pad with chr(0) since that's what mcrypt_generic does. to quote from {@link http://www.php.net/function.mcrypt-generic}:
  852. // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
  853. $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
  854. }
  855. $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
  856. if (!$this->continuousBuffer) {
  857. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  858. }
  859. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  860. }
  861. if ($this->changed) {
  862. $this->_setup();
  863. $this->changed = false;
  864. }
  865. if ($this->use_inline_crypt) {
  866. $inline = $this->inline_crypt;
  867. return $inline('decrypt', $this, $ciphertext);
  868. }
  869. $block_size = $this->block_size;
  870. if ($this->paddable) {
  871. // we pad with chr(0) since that's what mcrypt_generic does [...]
  872. $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
  873. }
  874. $buffer = &$this->debuffer;
  875. $plaintext = '';
  876. switch ($this->mode) {
  877. case CRYPT_MODE_ECB:
  878. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  879. $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size));
  880. }
  881. break;
  882. case CRYPT_MODE_CBC:
  883. $xor = $this->decryptIV;
  884. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  885. $block = substr($ciphertext, $i, $block_size);
  886. $plaintext.= $this->_decryptBlock($block) ^ $xor;
  887. $xor = $block;
  888. }
  889. if ($this->continuousBuffer) {
  890. $this->decryptIV = $xor;
  891. }
  892. break;
  893. case CRYPT_MODE_CTR:
  894. $xor = $this->decryptIV;
  895. if (strlen($buffer['ciphertext'])) {
  896. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  897. $block = substr($ciphertext, $i, $block_size);
  898. if (strlen($block) > strlen($buffer['ciphertext'])) {
  899. $buffer['ciphertext'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
  900. }
  901. $key = $this->_stringShift($buffer['ciphertext'], $block_size);
  902. $plaintext.= $block ^ $key;
  903. }
  904. } else {
  905. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  906. $block = substr($ciphertext, $i, $block_size);
  907. $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
  908. $plaintext.= $block ^ $key;
  909. }
  910. }
  911. if ($this->continuousBuffer) {
  912. $this->decryptIV = $xor;
  913. if ($start = strlen($ciphertext) % $block_size) {
  914. $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
  915. }
  916. }
  917. break;
  918. case CRYPT_MODE_CFB:
  919. if ($this->continuousBuffer) {
  920. $iv = &$this->decryptIV;
  921. $pos = &$buffer['pos'];
  922. } else {
  923. $iv = $this->decryptIV;
  924. $pos = 0;
  925. }
  926. $len = strlen($ciphertext);
  927. $i = 0;
  928. if ($pos) {
  929. $orig_pos = $pos;
  930. $max = $block_size - $pos;
  931. if ($len >= $max) {
  932. $i = $max;
  933. $len-= $max;
  934. $pos = 0;
  935. } else {
  936. $i = $len;
  937. $pos+= $len;
  938. $len = 0;
  939. }
  940. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  941. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  942. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  943. }
  944. while ($len >= $block_size) {
  945. $iv = $this->_encryptBlock($iv);
  946. $cb = substr($ciphertext, $i, $block_size);
  947. $plaintext.= $iv ^ $cb;
  948. $iv = $cb;
  949. $len-= $block_size;
  950. $i+= $block_size;
  951. }
  952. if ($len) {
  953. $iv = $this->_encryptBlock($iv);
  954. $plaintext.= $iv ^ substr($ciphertext, $i);
  955. $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
  956. $pos = $len;
  957. }
  958. break;
  959. case CRYPT_MODE_OFB:
  960. $xor = $this->decryptIV;
  961. if (strlen($buffer['xor'])) {
  962. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  963. $block = substr($ciphertext, $i, $block_size);
  964. if (strlen($block) > strlen($buffer['xor'])) {
  965. $xor = $this->_encryptBlock($xor);
  966. $buffer['xor'].= $xor;
  967. }
  968. $key = $this->_stringShift($buffer['xor'], $block_size);
  969. $plaintext.= $block ^ $key;
  970. }
  971. } else {
  972. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  973. $xor = $this->_encryptBlock($xor);
  974. $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor;
  975. }
  976. $key = $xor;
  977. }
  978. if ($this->continuousBuffer) {
  979. $this->decryptIV = $xor;
  980. if ($start = strlen($ciphertext) % $block_size) {
  981. $buffer['xor'] = substr($key, $start) . $buffer['xor'];
  982. }
  983. }
  984. break;
  985. case CRYPT_MODE_STREAM:
  986. $plaintext = $this->_decryptBlock($ciphertext);
  987. break;
  988. }
  989. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  990. }
  991. /**
  992. * Pad "packets".
  993. *
  994. * Block ciphers working by encrypting between their specified [$this->]block_size at a time
  995. * If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to
  996. * pad the input so that it is of the proper length.
  997. *
  998. * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH,
  999. * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
  1000. * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
  1001. * transmitted separately)
  1002. *
  1003. * @see Crypt_Base::disablePadding()
  1004. * @access public
  1005. */
  1006. function enablePadding()
  1007. {
  1008. $this->padding = true;
  1009. }
  1010. /**
  1011. * Do not pad packets.
  1012. *
  1013. * @see Crypt_Base::enablePadding()
  1014. * @access public
  1015. */
  1016. function disablePadding()
  1017. {
  1018. $this->padding = false;
  1019. }
  1020. /**
  1021. * Treat consecutive "packets" as if they are a continuous buffer.
  1022. *
  1023. * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets
  1024. * will yield different outputs:
  1025. *
  1026. * <code>
  1027. * echo $rijndael->encrypt(substr($plaintext, 0, 16));
  1028. * echo $rijndael->encrypt(substr($plaintext, 16, 16));
  1029. * </code>
  1030. * <code>
  1031. * echo $rijndael->encrypt($plaintext);
  1032. * </code>
  1033. *
  1034. * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
  1035. * another, as demonstrated with the following:
  1036. *
  1037. * <code>
  1038. * $rijndael->encrypt(substr($plaintext, 0, 16));
  1039. * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
  1040. * </code>
  1041. * <code>
  1042. * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
  1043. * </code>
  1044. *
  1045. * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
  1046. * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
  1047. * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
  1048. *
  1049. * Put another way, when the continuous buffer is enabled, the state of the Crypt_*() object changes after each
  1050. * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
  1051. * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
  1052. * however, they are also less intuitive and more likely to cause you problems.
  1053. *
  1054. * Note: Could, but not must, extend by the child Crypt_* class
  1055. *
  1056. * @see Crypt_Base::disableContinuousBuffer()
  1057. * @access public
  1058. */
  1059. function enableContinuousBuffer()
  1060. {
  1061. if ($this->mode == CRYPT_MODE_ECB) {
  1062. return;
  1063. }
  1064. $this->continuousBuffer = true;
  1065. }
  1066. /**
  1067. * Treat consecutive packets as if they are a discontinuous buffer.
  1068. *
  1069. * The default behavior.
  1070. *
  1071. * Note: Could, but not must, extend by the child Crypt_* class
  1072. *
  1073. * @see Crypt_Base::enableContinuousBuffer()
  1074. * @access public
  1075. */
  1076. function disableContinuousBuffer()
  1077. {
  1078. if ($this->mode == CRYPT_MODE_ECB) {
  1079. return;
  1080. }
  1081. if (!$this->continuousBuffer) {
  1082. return;
  1083. }
  1084. $this->continuousBuffer = false;
  1085. $this->changed = true;
  1086. }
  1087. /**
  1088. * Encrypts a block
  1089. *
  1090. * Note: Must extend by the child Crypt_* class
  1091. *
  1092. * @access private
  1093. * @param String $in
  1094. * @return String
  1095. */
  1096. function _encryptBlock($in)
  1097. {
  1098. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1099. }
  1100. /**
  1101. * Decrypts a block
  1102. *
  1103. * Note: Must extend by the child Crypt_* class
  1104. *
  1105. * @access private
  1106. * @param String $in
  1107. * @return String
  1108. */
  1109. function _decryptBlock($in)
  1110. {
  1111. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1112. }
  1113. /**
  1114. * Setup the key (expansion)
  1115. *
  1116. * Only used if $engine == CRYPT_MODE_INTERNAL
  1117. *
  1118. * Note: Must extend by the child Crypt_* class
  1119. *
  1120. * @see Crypt_Base::_setup()
  1121. * @access private
  1122. */
  1123. function _setupKey()
  1124. {
  1125. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1126. }
  1127. /**
  1128. * Setup the CRYPT_MODE_INTERNAL $engine
  1129. *
  1130. * (re)init, if necessary, the internal cipher $engine and flush all $buffers
  1131. * Used (only) if $engine == CRYPT_MODE_INTERNAL
  1132. *
  1133. * _setup() will be called each time if $changed === true
  1134. * typically this happens when using one or more of following public methods:
  1135. *
  1136. * - setKey()
  1137. *
  1138. * - setIV()
  1139. *
  1140. * - disableContinuousBuffer()
  1141. *
  1142. * - First run of encrypt() / decrypt() with no init-settings
  1143. *
  1144. * Internally: _setup() is called always before(!) en/decryption.
  1145. *
  1146. * Note: Could, but not must, extend by the child Crypt_* class
  1147. *
  1148. * @see setKey()
  1149. * @see setIV()
  1150. * @see disableContinuousBuffer()
  1151. * @access private
  1152. */
  1153. function _setup()
  1154. {
  1155. $this->_clearBuffers();
  1156. $this->_setupKey();
  1157. if ($this->use_inline_crypt) {
  1158. $this->_setupInlineCrypt();
  1159. }
  1160. }
  1161. /**
  1162. * Setup the CRYPT_MODE_MCRYPT $engine
  1163. *
  1164. * (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers
  1165. * Used (only) if $engine = CRYPT_MODE_MCRYPT
  1166. *
  1167. * _setupMcrypt() will be called each time if $changed === true
  1168. * typically this happens when using one or more of following public methods:
  1169. *
  1170. * - setKey()
  1171. *
  1172. * - setIV()
  1173. *
  1174. * - disableContinuousBuffer()
  1175. *
  1176. * - First run of encrypt() / decrypt()
  1177. *
  1178. *
  1179. * Note: Could, but not must, extend by the child Crypt_* class
  1180. *
  1181. * @see setKey()
  1182. * @see setIV()
  1183. * @see disableContinuousBuffer()
  1184. * @access private
  1185. */
  1186. function _setupMcrypt()
  1187. {
  1188. $this->_clearBuffers();
  1189. $this->enchanged = $this->dechanged = true;
  1190. if (!isset($this->enmcrypt)) {
  1191. static $mcrypt_modes = array(
  1192. CRYPT_MODE_CTR => 'ctr',
  1193. CRYPT_MODE_ECB => MCRYPT_MODE_ECB,
  1194. CRYPT_MODE_CBC => MCRYPT_MODE_CBC,
  1195. CRYPT_MODE_CFB => 'ncfb',
  1196. CRYPT_MODE_OFB => MCRYPT_MODE_NOFB,
  1197. CRYPT_MODE_STREAM => MCRYPT_MODE_STREAM,
  1198. );
  1199. $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
  1200. $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
  1201. // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
  1202. // to workaround mcrypt's broken ncfb implementation in buffered mode
  1203. // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
  1204. if ($this->mode == CRYPT_MODE_CFB) {
  1205. $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
  1206. }
  1207. } // else should mcrypt_generic_deinit be called?
  1208. if ($this->mode == CRYPT_MODE_CFB) {
  1209. mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
  1210. }
  1211. }
  1212. /**
  1213. * Pads a string
  1214. *
  1215. * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize.
  1216. * $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to
  1217. * chr($this->block_size - (strlen($text) % $this->block_size)
  1218. *
  1219. * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
  1220. * and padding will, hence forth, be enabled.
  1221. *
  1222. * @see Crypt_Base::_unpad()
  1223. * @param String $text
  1224. * @access private
  1225. * @return String
  1226. */
  1227. function _pad($text)
  1228. {
  1229. $length = strlen($text);
  1230. if (!$this->padding) {
  1231. if ($length % $this->block_size == 0) {
  1232. return $text;
  1233. } else {
  1234. user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})");
  1235. $this->padding = true;
  1236. }
  1237. }
  1238. $pad = $this->block_size - ($length % $this->block_size);
  1239. return str_pad($text, $length + $pad, chr($pad));
  1240. }
  1241. /**
  1242. * Unpads a string.
  1243. *
  1244. * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
  1245. * and false will be returned.
  1246. *
  1247. * @see Crypt_Base::_pad()
  1248. * @param String $text
  1249. * @access private
  1250. * @return String
  1251. */
  1252. function _unpad($text)
  1253. {
  1254. if (!$this->padding) {
  1255. return $text;
  1256. }
  1257. $length = ord($text[strlen($text) - 1]);
  1258. if (!$length || $length > $this->block_size) {
  1259. return false;
  1260. }
  1261. return substr($text, 0, -$length);
  1262. }
  1263. /**
  1264. * Clears internal buffers
  1265. *
  1266. * Clearing/resetting the internal buffers is done everytime
  1267. * after disableContinuousBuffer() or on cipher $engine (re)init
  1268. * ie after setKey() or setIV()
  1269. *
  1270. * Note: Could, but not must, extend by the child Crypt_* class
  1271. *
  1272. * @access public
  1273. */
  1274. function _clearBuffers()
  1275. {
  1276. $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
  1277. $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
  1278. // mcrypt's handling of invalid's $iv:
  1279. // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size);
  1280. $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0");
  1281. }
  1282. /**
  1283. * String Shift
  1284. *
  1285. * Inspired by array_shift
  1286. *
  1287. * @param String $string
  1288. * @param optional Integer $index
  1289. * @access private
  1290. * @return String
  1291. */
  1292. function _stringShift(&$string, $index = 1)
  1293. {
  1294. $substr = substr($string, 0, $index);
  1295. $string = substr($string, $index);
  1296. return $substr;
  1297. }
  1298. /**
  1299. * Generate CTR XOR encryption key
  1300. *
  1301. * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
  1302. * plaintext / ciphertext in CTR mode.
  1303. *
  1304. * @see Crypt_Base::decrypt()
  1305. * @see Crypt_Base::encrypt()
  1306. * @param String $iv
  1307. * @param Integer $length
  1308. * @access private
  1309. * @return String $xor
  1310. */
  1311. function _generateXor(&$iv, $length)
  1312. {
  1313. $xor = '';
  1314. $block_size = $this->block_size;
  1315. $num_blocks = floor(($length + ($block_size - 1)) / $block_size);
  1316. for ($i = 0; $i < $num_blocks; $i++) {
  1317. $xor.= $iv;
  1318. for ($j = 4; $j <= $block_size; $j+= 4) {
  1319. $temp = substr($iv, -$j, 4);
  1320. switch ($temp) {
  1321. case "\xFF\xFF\xFF\xFF":
  1322. $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
  1323. break;
  1324. case "\x7F\xFF\xFF\xFF":
  1325. $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
  1326. break 2;
  1327. default:
  1328. extract(unpack('Ncount', $temp));
  1329. $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
  1330. break 2;
  1331. }
  1332. }
  1333. }
  1334. return $xor;
  1335. }
  1336. /**
  1337. * Setup the performance-optimized function for de/encrypt()
  1338. *
  1339. * Stores the created (or existing) callback function-name
  1340. * in $this->inline_crypt
  1341. *
  1342. * Internally for phpseclib developers:
  1343. *
  1344. * _setupInlineCrypt() would be called only if:
  1345. *
  1346. * - $engine == CRYPT_MODE_INTERNAL and
  1347. *
  1348. * - $use_inline_crypt === true
  1349. *
  1350. * - each time on _setup(), after(!) _setupKey()
  1351. *
  1352. *
  1353. * This ensures that _setupInlineCrypt() has allways a
  1354. * full ready2go initializated internal cipher $engine state
  1355. * where, for example, the keys allready expanded,
  1356. * keys/block_size calculated and such.
  1357. *
  1358. * It is, each time if called, the responsibility of _setupInlineCrypt():
  1359. *
  1360. * - to set $this->inline_crypt to a valid and fully working callback function
  1361. * …

Large files files are truncated, but you can click here to view the full file