PageRenderTime 32ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/php5-3/core/tools/secure/crypt/Base.class.php

https://bitbucket.org/ronaldobrandini/framework
PHP | 1934 lines | 1097 code | 95 blank | 742 comment | 102 complexity | 157b6d0e244a322a501f2630e0112207 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  1. <?php
  2. namespace core\tools\secure\crypt;
  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 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 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 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. * @link http://phpseclib.sourceforge.net
  53. */
  54. /* * #@+
  55. * @access public
  56. * @see Base::encrypt()
  57. * @see Base::decrypt()
  58. */
  59. /**
  60. * Base Class for all Crypt_* cipher classes
  61. *
  62. * @package Base
  63. * @author Jim Wigginton <terrafrost@php.net>
  64. * @author Hans-Juergen Petrich <petrich@tronic-media.com>
  65. * @access public
  66. */
  67. class Base{
  68. /**
  69. * The Encryption Mode
  70. *
  71. * @see Base::Base()
  72. * @var Integer
  73. * @access private
  74. */
  75. private $mode;
  76. /**
  77. * The Block Length of the block cipher
  78. *
  79. * @var Integer
  80. * @access private
  81. */
  82. protected $block_size = 16;
  83. /**
  84. * The Key
  85. *
  86. * @see Base::setKey()
  87. * @var String
  88. * @access private
  89. */
  90. protected $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
  91. /**
  92. * The Initialization Vector
  93. *
  94. * @see Base::setIV()
  95. * @var String
  96. * @access private
  97. */
  98. private $iv;
  99. /**
  100. * A "sliding" Initialization Vector
  101. *
  102. * @see Base::enableContinuousBuffer()
  103. * @see Base::_clearBuffers()
  104. * @var String
  105. * @access private
  106. */
  107. private $encryptIV;
  108. /**
  109. * A "sliding" Initialization Vector
  110. *
  111. * @see Base::enableContinuousBuffer()
  112. * @see Base::_clearBuffers()
  113. * @var String
  114. * @access private
  115. */
  116. private $decryptIV;
  117. /**
  118. * Continuous Buffer status
  119. *
  120. * @see Base::enableContinuousBuffer()
  121. * @var Boolean
  122. * @access private
  123. */
  124. private $continuousBuffer = false;
  125. /**
  126. * Encryption buffer for CTR, OFB and CFB modes
  127. *
  128. * @see Base::encrypt()
  129. * @see Base::_clearBuffers()
  130. * @var Array
  131. * @access private
  132. */
  133. private $enbuffer;
  134. /**
  135. * Decryption buffer for CTR, OFB and CFB modes
  136. *
  137. * @see Base::decrypt()
  138. * @see Base::_clearBuffers()
  139. * @var Array
  140. * @access private
  141. */
  142. private $debuffer;
  143. /**
  144. * mcrypt resource for encryption
  145. *
  146. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  147. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  148. *
  149. * @see Base::encrypt()
  150. * @var Resource
  151. * @access private
  152. */
  153. private $enmcrypt;
  154. /**
  155. * mcrypt resource for decryption
  156. *
  157. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  158. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  159. *
  160. * @see Base::decrypt()
  161. * @var Resource
  162. * @access private
  163. */
  164. private $demcrypt;
  165. /**
  166. * Does the enmcrypt resource need to be (re)initialized?
  167. *
  168. * @see Crypt_Twofish::setKey()
  169. * @see Crypt_Twofish::setIV()
  170. * @var Boolean
  171. * @access private
  172. */
  173. private $enchanged = true;
  174. /**
  175. * Does the demcrypt resource need to be (re)initialized?
  176. *
  177. * @see Crypt_Twofish::setKey()
  178. * @see Crypt_Twofish::setIV()
  179. * @var Boolean
  180. * @access private
  181. */
  182. private $dechanged = true;
  183. /**
  184. * mcrypt resource for CFB mode
  185. *
  186. * mcrypt's CFB mode, in (and only in) buffered context,
  187. * is broken, so phpseclib implements the CFB mode by it self,
  188. * even when the mcrypt php extension is available.
  189. *
  190. * In order to do the CFB-mode work (fast) phpseclib
  191. * use a separate ECB-mode mcrypt resource.
  192. *
  193. * @link http://phpseclib.sourceforge.net/cfb-demo.phps
  194. * @see Base::encrypt()
  195. * @see Base::decrypt()
  196. * @see Base::_setupMcrypt()
  197. * @var Resource
  198. * @access private
  199. */
  200. private $ecb;
  201. /**
  202. * Optimizing value while CFB-encrypting
  203. *
  204. * Only relevant if $continuousBuffer enabled
  205. * and $engine == CRYPT_MODE_MCRYPT
  206. *
  207. * It's faster to re-init $enmcrypt if
  208. * $buffer bytes > $cfb_init_len than
  209. * using the $ecb resource furthermore.
  210. *
  211. * This value depends of the chosen cipher
  212. * and the time it would be needed for it's
  213. * initialization [by mcrypt_generic_init()]
  214. * which, typically, depends on the complexity
  215. * on its internaly Key-expanding algorithm.
  216. *
  217. * @see Base::encrypt()
  218. * @var Integer
  219. * @access private
  220. */
  221. private $cfb_init_len = 600;
  222. /**
  223. * Does internal cipher state need to be (re)initialized?
  224. *
  225. * @see setKey()
  226. * @see setIV()
  227. * @see disableContinuousBuffer()
  228. * @var Boolean
  229. * @access private
  230. */
  231. private $changed = true;
  232. /**
  233. * Padding status
  234. *
  235. * @see Base::enablePadding()
  236. * @var Boolean
  237. * @access private
  238. */
  239. private $padding = true;
  240. /**
  241. * Is the mode one that is paddable?
  242. *
  243. * @see Base::Base()
  244. * @var Boolean
  245. * @access private
  246. */
  247. private $paddable = false;
  248. /**
  249. * Holds which crypt engine internaly should be use,
  250. * which will be determined automatically on __construct()
  251. *
  252. * Currently available $engines are:
  253. * - CRYPT_MODE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required)
  254. * - CRYPT_MODE_INTERNAL (slower, pure php-engine, no php-extension required)
  255. *
  256. * In the pipeline... maybe. But currently not available:
  257. * - CRYPT_MODE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required)
  258. *
  259. * If possible, CRYPT_MODE_MCRYPT will be used for each cipher.
  260. * Otherwise CRYPT_MODE_INTERNAL
  261. *
  262. * @see Base::encrypt()
  263. * @see Base::decrypt()
  264. * @var Integer
  265. * @access private
  266. */
  267. protected $engine;
  268. /**
  269. * The mcrypt specific name of the cipher
  270. *
  271. * Only used if $engine == CRYPT_MODE_MCRYPT
  272. *
  273. * @link http://www.php.net/mcrypt_module_open
  274. * @link http://www.php.net/mcrypt_list_algorithms
  275. * @see Base::_setupMcrypt()
  276. * @var String
  277. * @access private
  278. */
  279. private $cipher_name_mcrypt;
  280. /**
  281. * The default password key_size used by setPassword()
  282. *
  283. * @see Base::setPassword()
  284. * @var Integer
  285. * @access private
  286. */
  287. private $password_key_size = 32;
  288. /**
  289. * The default salt used by setPassword()
  290. *
  291. * @see Base::setPassword()
  292. * @var String
  293. * @access private
  294. */
  295. private $password_default_salt = 'phpseclib/salt';
  296. /**
  297. * The namespace used by the cipher for its constants.
  298. *
  299. * ie: AES.php is using CRYPT_AES_MODE_* for its constants
  300. * so $const_namespace is AES
  301. *
  302. * DES.php is using CRYPT_DES_MODE_* for its constants
  303. * so $const_namespace is DES... and so on
  304. *
  305. * All CRYPT_<$const_namespace>_MODE_* are aliases of
  306. * the generic CRYPT_MODE_* constants, so both could be used
  307. * for each cipher.
  308. *
  309. * Example:
  310. * $aes = new Crypt_AES(CRYPT_AES_MODE_CFB); // $aes will operate in cfb mode
  311. * $aes = new Crypt_AES(CRYPT_MODE_CFB); // identical
  312. *
  313. * @see Base::Base()
  314. * @var String
  315. * @access private
  316. */
  317. protected $const_namespace;
  318. /**
  319. * The name of the performance-optimized callback function
  320. *
  321. * Used by encrypt() / decrypt()
  322. * only if $engine == CRYPT_MODE_INTERNAL
  323. *
  324. * @see Base::encrypt()
  325. * @see Base::decrypt()
  326. * @see Base::_setupInlineCrypt()
  327. * @see Base::$use_inline_crypt
  328. * @var Callback
  329. * @access private
  330. */
  331. private $inline_crypt;
  332. /**
  333. * Holds whether performance-optimized $inline_crypt() can/should be used.
  334. *
  335. * @see Base::encrypt()
  336. * @see Base::decrypt()
  337. * @see Base::inline_crypt
  338. * @var mixed
  339. * @access private
  340. */
  341. protected $use_inline_crypt;
  342. /**
  343. * Default Constructor.
  344. *
  345. * Determines whether or not the mcrypt extension should be used.
  346. *
  347. * $mode could be:
  348. *
  349. * - CRYPT_MODE_ECB
  350. *
  351. * - CRYPT_MODE_CBC
  352. *
  353. * - CRYPT_MODE_CTR
  354. *
  355. * - CRYPT_MODE_CFB
  356. *
  357. * - CRYPT_MODE_OFB
  358. *
  359. * (or the alias constants of the chosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...)
  360. *
  361. * If not explicitly set, CRYPT_MODE_CBC will be used.
  362. *
  363. * @param optional Integer $mode
  364. * @access public
  365. */
  366. public function __construct($mode = CRYPT_MODE_CBC){
  367. $const_crypt_mode = 'CRYPT_' . $this->const_namespace . '_MODE';
  368. // Determining the availibility of mcrypt support for the cipher
  369. if(!defined($const_crypt_mode)){
  370. switch(true){
  371. case extension_loaded('mcrypt') && in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms()):
  372. define($const_crypt_mode, CRYPT_MODE_MCRYPT);
  373. break;
  374. default:
  375. define($const_crypt_mode, CRYPT_MODE_INTERNAL);
  376. }
  377. }
  378. // Determining which internal $engine should be used.
  379. // The fastes possible first.
  380. switch(true){
  381. case empty($this->cipher_name_mcrypt): // The cipher module has no mcrypt-engine support at all so we force CRYPT_MODE_INTERNAL
  382. $this->engine = CRYPT_MODE_INTERNAL;
  383. break;
  384. case constant($const_crypt_mode) == CRYPT_MODE_MCRYPT:
  385. $this->engine = CRYPT_MODE_MCRYPT;
  386. break;
  387. default:
  388. $this->engine = CRYPT_MODE_INTERNAL;
  389. }
  390. // $mode dependent settings
  391. switch($mode){
  392. case CRYPT_MODE_ECB:
  393. $this->paddable = true;
  394. $this->mode = $mode;
  395. break;
  396. case CRYPT_MODE_CTR:
  397. case CRYPT_MODE_CFB:
  398. case CRYPT_MODE_OFB:
  399. case CRYPT_MODE_STREAM:
  400. $this->mode = $mode;
  401. break;
  402. case CRYPT_MODE_CBC:
  403. default:
  404. $this->paddable = true;
  405. $this->mode = CRYPT_MODE_CBC;
  406. }
  407. // Determining whether inline crypting can be used by the cipher
  408. if($this->use_inline_crypt !== false && function_exists('create_function')){
  409. $this->use_inline_crypt = true;
  410. }
  411. }
  412. /**
  413. * Sets the initialization vector. (optional)
  414. *
  415. * SetIV is not required when CRYPT_MODE_ECB (or ie for AES: CRYPT_AES_MODE_ECB) is being used. If not explicitly set, it'll be assumed
  416. * to be all zero's.
  417. *
  418. * Note: Could, but not must, extend by the child Crypt_* class
  419. *
  420. * @access public
  421. * @param String $iv
  422. */
  423. public function setIV($iv){
  424. if($this->mode == CRYPT_MODE_ECB){
  425. return;
  426. }
  427. $this->iv = $iv;
  428. $this->changed = true;
  429. }
  430. /**
  431. * Sets the key.
  432. *
  433. * The min/max length(s) of the key depends on the cipher which is used.
  434. * If the key not fits the length(s) of the cipher it will paded with null bytes
  435. * up to the closest valid key length. If the key is more than max length,
  436. * we trim the excess bits.
  437. *
  438. * If the key is not explicitly set, it'll be assumed to be all null bytes.
  439. *
  440. * Note: Could, but not must, extend by the child Crypt_* class
  441. *
  442. * @access public
  443. * @param String $key
  444. */
  445. public function setKey($key){
  446. $this->key = $key;
  447. $this->changed = true;
  448. }
  449. /**
  450. * Sets the password.
  451. *
  452. * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
  453. * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2} or pbkdf1:
  454. * $hash, $salt, $count, $dkLen
  455. *
  456. * Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php
  457. *
  458. * Note: Could, but not must, extend by the child Crypt_* class
  459. *
  460. * @see Crypt/Hash.php
  461. * @param String $password
  462. * @param optional String $method
  463. * @return Boolean
  464. * @access public
  465. */
  466. public function setPassword($password, $method = 'pbkdf2'){
  467. $key = '';
  468. switch($method){
  469. default: // 'pbkdf2' or 'pbkdf1'
  470. $func_args = func_get_args();
  471. // Hash function
  472. $hash = isset($func_args[2]) ? $func_args[2] : 'sha1';
  473. // WPA and WPA2 use the SSID as the salt
  474. $salt = isset($func_args[3]) ? $func_args[3] : $this->password_default_salt;
  475. // RFC2898#section-4.2 uses 1,000 iterations by default
  476. // WPA and WPA2 use 4,096.
  477. $count = isset($func_args[4]) ? $func_args[4] : 1000;
  478. // Keylength
  479. if(isset($func_args[5])){
  480. $dkLen = $func_args[5];
  481. }else{
  482. $dkLen = $method == 'pbkdf1' ? 2 * $this->password_key_size : $this->password_key_size;
  483. }
  484. switch(true){
  485. case $method == 'pbkdf1':
  486. if(!class_exists('Crypt_Hash')){
  487. include_once 'Crypt/Hash.php';
  488. }
  489. $hashObj = new Crypt_Hash();
  490. $hashObj->setHash($hash);
  491. if($dkLen > $hashObj->getLength()){
  492. user_error('Derived key too long');
  493. return false;
  494. }
  495. $t = $password . $salt;
  496. for($i = 0; $i < $count; ++$i){
  497. $t = $hashObj->hash($t);
  498. }
  499. $key = substr($t, 0, $dkLen);
  500. $this->setKey(substr($key, 0, $dkLen >> 1));
  501. $this->setIV(substr($key, $dkLen >> 1));
  502. return true;
  503. // Determining if php[>=5.5.0]'s hash_pbkdf2() function avail- and useable
  504. case!function_exists('hash_pbkdf2'):
  505. case!function_exists('hash_algos'):
  506. case!in_array($hash, hash_algos()):
  507. if(!class_exists('Crypt_Hash')){
  508. include_once 'Crypt/Hash.php';
  509. }
  510. $i = 1;
  511. while(strlen($key) < $dkLen){
  512. $hmac = new Crypt_Hash();
  513. $hmac->setHash($hash);
  514. $hmac->setKey($password);
  515. $f = $u = $hmac->hash($salt . pack('N', $i++));
  516. for($j = 2; $j <= $count; ++$j){
  517. $u = $hmac->hash($u);
  518. $f^= $u;
  519. }
  520. $key.= $f;
  521. }
  522. $key = substr($key, 0, $dkLen);
  523. break;
  524. default:
  525. $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true);
  526. }
  527. }
  528. $this->setKey($key);
  529. return true;
  530. }
  531. /**
  532. * Encrypts a message.
  533. *
  534. * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher
  535. * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's
  536. * necessary are discussed in the following
  537. * URL:
  538. *
  539. * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
  540. *
  541. * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
  542. * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that
  543. * length.
  544. *
  545. * Note: Could, but not must, extend by the child Crypt_* class
  546. *
  547. * @see Base::decrypt()
  548. * @access public
  549. * @param String $plaintext
  550. * @return String $cipertext
  551. */
  552. public function encrypt($plaintext){
  553. if($this->engine == CRYPT_MODE_MCRYPT){
  554. if($this->changed){
  555. $this->_setupMcrypt();
  556. $this->changed = false;
  557. }
  558. if($this->enchanged){
  559. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  560. $this->enchanged = false;
  561. }
  562. // re: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
  563. // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
  564. // rewritten CFB implementation the above outputs the same thing twice.
  565. if($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer){
  566. $block_size = $this->block_size;
  567. $iv = &$this->encryptIV;
  568. $pos = &$this->enbuffer['pos'];
  569. $len = strlen($plaintext);
  570. $ciphertext = '';
  571. $i = 0;
  572. if($pos){
  573. $orig_pos = $pos;
  574. $max = $block_size - $pos;
  575. if($len >= $max){
  576. $i = $max;
  577. $len-= $max;
  578. $pos = 0;
  579. }else{
  580. $i = $len;
  581. $pos+= $len;
  582. $len = 0;
  583. }
  584. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  585. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  586. $this->enbuffer['enmcrypt_init'] = true;
  587. }
  588. if($len >= $block_size){
  589. if($this->enbuffer['enmcrypt_init'] === false || $len > $this->cfb_init_len){
  590. if($this->enbuffer['enmcrypt_init'] === true){
  591. mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
  592. $this->enbuffer['enmcrypt_init'] = false;
  593. }
  594. $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size));
  595. $iv = substr($ciphertext, -$block_size);
  596. $len%= $block_size;
  597. }else{
  598. while($len >= $block_size){
  599. $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size);
  600. $ciphertext.= $iv;
  601. $len-= $block_size;
  602. $i+= $block_size;
  603. }
  604. }
  605. }
  606. if($len){
  607. $iv = mcrypt_generic($this->ecb, $iv);
  608. $block = $iv ^ substr($plaintext, -$len);
  609. $iv = substr_replace($iv, $block, 0, $len);
  610. $ciphertext.= $block;
  611. $pos = $len;
  612. }
  613. return $ciphertext;
  614. }
  615. if($this->paddable){
  616. $plaintext = $this->_pad($plaintext);
  617. }
  618. $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
  619. if(!$this->continuousBuffer){
  620. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  621. }
  622. return $ciphertext;
  623. }
  624. if($this->changed){
  625. $this->_setup();
  626. $this->changed = false;
  627. }
  628. if($this->use_inline_crypt){
  629. $inline = $this->inline_crypt;
  630. return $inline('encrypt', $this, $plaintext);
  631. }
  632. if($this->paddable){
  633. $plaintext = $this->_pad($plaintext);
  634. }
  635. $buffer = &$this->enbuffer;
  636. $block_size = $this->block_size;
  637. $ciphertext = '';
  638. switch($this->mode){
  639. case CRYPT_MODE_ECB:
  640. for($i = 0; $i < strlen($plaintext); $i+=$block_size){
  641. $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));
  642. }
  643. break;
  644. case CRYPT_MODE_CBC:
  645. $xor = $this->encryptIV;
  646. for($i = 0; $i < strlen($plaintext); $i+=$block_size){
  647. $block = substr($plaintext, $i, $block_size);
  648. $block = $this->_encryptBlock($block ^ $xor);
  649. $xor = $block;
  650. $ciphertext.= $block;
  651. }
  652. if($this->continuousBuffer){
  653. $this->encryptIV = $xor;
  654. }
  655. break;
  656. case CRYPT_MODE_CTR:
  657. $xor = $this->encryptIV;
  658. if(strlen($buffer['encrypted'])){
  659. for($i = 0; $i < strlen($plaintext); $i+=$block_size){
  660. $block = substr($plaintext, $i, $block_size);
  661. if(strlen($block) > strlen($buffer['encrypted'])){
  662. $buffer['encrypted'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
  663. }
  664. $key = $this->_stringShift($buffer['encrypted'], $block_size);
  665. $ciphertext.= $block ^ $key;
  666. }
  667. }else{
  668. for($i = 0; $i < strlen($plaintext); $i+=$block_size){
  669. $block = substr($plaintext, $i, $block_size);
  670. $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
  671. $ciphertext.= $block ^ $key;
  672. }
  673. }
  674. if($this->continuousBuffer){
  675. $this->encryptIV = $xor;
  676. if($start = strlen($plaintext) % $block_size){
  677. $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
  678. }
  679. }
  680. break;
  681. case CRYPT_MODE_CFB:
  682. // cfb loosely routines inspired by openssl's:
  683. // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1}
  684. if($this->continuousBuffer){
  685. $iv = &$this->encryptIV;
  686. $pos = &$buffer['pos'];
  687. }else{
  688. $iv = $this->encryptIV;
  689. $pos = 0;
  690. }
  691. $len = strlen($plaintext);
  692. $i = 0;
  693. if($pos){
  694. $orig_pos = $pos;
  695. $max = $block_size - $pos;
  696. if($len >= $max){
  697. $i = $max;
  698. $len-= $max;
  699. $pos = 0;
  700. }else{
  701. $i = $len;
  702. $pos+= $len;
  703. $len = 0;
  704. }
  705. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  706. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  707. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  708. }
  709. while($len >= $block_size){
  710. $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size);
  711. $ciphertext.= $iv;
  712. $len-= $block_size;
  713. $i+= $block_size;
  714. }
  715. if($len){
  716. $iv = $this->_encryptBlock($iv);
  717. $block = $iv ^ substr($plaintext, $i);
  718. $iv = substr_replace($iv, $block, 0, $len);
  719. $ciphertext.= $block;
  720. $pos = $len;
  721. }
  722. break;
  723. case CRYPT_MODE_OFB:
  724. $xor = $this->encryptIV;
  725. if(strlen($buffer['xor'])){
  726. for($i = 0; $i < strlen($plaintext); $i+=$block_size){
  727. $block = substr($plaintext, $i, $block_size);
  728. if(strlen($block) > strlen($buffer['xor'])){
  729. $xor = $this->_encryptBlock($xor);
  730. $buffer['xor'].= $xor;
  731. }
  732. $key = $this->_stringShift($buffer['xor'], $block_size);
  733. $ciphertext.= $block ^ $key;
  734. }
  735. }else{
  736. for($i = 0; $i < strlen($plaintext); $i+=$block_size){
  737. $xor = $this->_encryptBlock($xor);
  738. $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor;
  739. }
  740. $key = $xor;
  741. }
  742. if($this->continuousBuffer){
  743. $this->encryptIV = $xor;
  744. if($start = strlen($plaintext) % $block_size){
  745. $buffer['xor'] = substr($key, $start) . $buffer['xor'];
  746. }
  747. }
  748. break;
  749. case CRYPT_MODE_STREAM:
  750. $ciphertext = $this->_encryptBlock($plaintext);
  751. break;
  752. }
  753. return $ciphertext;
  754. }
  755. /**
  756. * Decrypts a message.
  757. *
  758. * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until
  759. * it is.
  760. *
  761. * Note: Could, but not must, extend by the child Crypt_* class
  762. *
  763. * @see Base::encrypt()
  764. * @access public
  765. * @param String $ciphertext
  766. * @return String $plaintext
  767. */
  768. public function decrypt($ciphertext){
  769. if($this->engine == CRYPT_MODE_MCRYPT){
  770. $block_size = $this->block_size;
  771. if($this->changed){
  772. $this->_setupMcrypt();
  773. $this->changed = false;
  774. }
  775. if($this->dechanged){
  776. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  777. $this->dechanged = false;
  778. }
  779. if($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer){
  780. $iv = &$this->decryptIV;
  781. $pos = &$this->debuffer['pos'];
  782. $len = strlen($ciphertext);
  783. $plaintext = '';
  784. $i = 0;
  785. if($pos){
  786. $orig_pos = $pos;
  787. $max = $block_size - $pos;
  788. if($len >= $max){
  789. $i = $max;
  790. $len-= $max;
  791. $pos = 0;
  792. }else{
  793. $i = $len;
  794. $pos+= $len;
  795. $len = 0;
  796. }
  797. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  798. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  799. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  800. }
  801. if($len >= $block_size){
  802. $cb = substr($ciphertext, $i, $len - $len % $block_size);
  803. $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
  804. $iv = substr($cb, -$block_size);
  805. $len%= $block_size;
  806. }
  807. if($len){
  808. $iv = mcrypt_generic($this->ecb, $iv);
  809. $plaintext.= $iv ^ substr($ciphertext, -$len);
  810. $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
  811. $pos = $len;
  812. }
  813. return $plaintext;
  814. }
  815. if($this->paddable){
  816. // we pad with chr(0) since that's what mcrypt_generic does. to quote from {@link http://www.php.net/function.mcrypt-generic}:
  817. // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
  818. $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
  819. }
  820. $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
  821. if(!$this->continuousBuffer){
  822. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  823. }
  824. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  825. }
  826. if($this->changed){
  827. $this->_setup();
  828. $this->changed = false;
  829. }
  830. if($this->use_inline_crypt){
  831. $inline = $this->inline_crypt;
  832. return $inline('decrypt', $this, $ciphertext);
  833. }
  834. $block_size = $this->block_size;
  835. if($this->paddable){
  836. // we pad with chr(0) since that's what mcrypt_generic does [...]
  837. $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
  838. }
  839. $buffer = &$this->debuffer;
  840. $plaintext = '';
  841. switch($this->mode){
  842. case CRYPT_MODE_ECB:
  843. for($i = 0; $i < strlen($ciphertext); $i+=$block_size){
  844. $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size));
  845. }
  846. break;
  847. case CRYPT_MODE_CBC:
  848. $xor = $this->decryptIV;
  849. for($i = 0; $i < strlen($ciphertext); $i+=$block_size){
  850. $block = substr($ciphertext, $i, $block_size);
  851. $plaintext.= $this->_decryptBlock($block) ^ $xor;
  852. $xor = $block;
  853. }
  854. if($this->continuousBuffer){
  855. $this->decryptIV = $xor;
  856. }
  857. break;
  858. case CRYPT_MODE_CTR:
  859. $xor = $this->decryptIV;
  860. if(strlen($buffer['ciphertext'])){
  861. for($i = 0; $i < strlen($ciphertext); $i+=$block_size){
  862. $block = substr($ciphertext, $i, $block_size);
  863. if(strlen($block) > strlen($buffer['ciphertext'])){
  864. $buffer['ciphertext'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
  865. }
  866. $key = $this->_stringShift($buffer['ciphertext'], $block_size);
  867. $plaintext.= $block ^ $key;
  868. }
  869. }else{
  870. for($i = 0; $i < strlen($ciphertext); $i+=$block_size){
  871. $block = substr($ciphertext, $i, $block_size);
  872. $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
  873. $plaintext.= $block ^ $key;
  874. }
  875. }
  876. if($this->continuousBuffer){
  877. $this->decryptIV = $xor;
  878. if($start = strlen($ciphertext) % $block_size){
  879. $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
  880. }
  881. }
  882. break;
  883. case CRYPT_MODE_CFB:
  884. if($this->continuousBuffer){
  885. $iv = &$this->decryptIV;
  886. $pos = &$buffer['pos'];
  887. }else{
  888. $iv = $this->decryptIV;
  889. $pos = 0;
  890. }
  891. $len = strlen($ciphertext);
  892. $i = 0;
  893. if($pos){
  894. $orig_pos = $pos;
  895. $max = $block_size - $pos;
  896. if($len >= $max){
  897. $i = $max;
  898. $len-= $max;
  899. $pos = 0;
  900. }else{
  901. $i = $len;
  902. $pos+= $len;
  903. $len = 0;
  904. }
  905. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  906. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  907. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  908. }
  909. while($len >= $block_size){
  910. $iv = $this->_encryptBlock($iv);
  911. $cb = substr($ciphertext, $i, $block_size);
  912. $plaintext.= $iv ^ $cb;
  913. $iv = $cb;
  914. $len-= $block_size;
  915. $i+= $block_size;
  916. }
  917. if($len){
  918. $iv = $this->_encryptBlock($iv);
  919. $plaintext.= $iv ^ substr($ciphertext, $i);
  920. $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
  921. $pos = $len;
  922. }
  923. break;
  924. case CRYPT_MODE_OFB:
  925. $xor = $this->decryptIV;
  926. if(strlen($buffer['xor'])){
  927. for($i = 0; $i < strlen($ciphertext); $i+=$block_size){
  928. $block = substr($ciphertext, $i, $block_size);
  929. if(strlen($block) > strlen($buffer['xor'])){
  930. $xor = $this->_encryptBlock($xor);
  931. $buffer['xor'].= $xor;
  932. }
  933. $key = $this->_stringShift($buffer['xor'], $block_size);
  934. $plaintext.= $block ^ $key;
  935. }
  936. }else{
  937. for($i = 0; $i < strlen($ciphertext); $i+=$block_size){
  938. $xor = $this->_encryptBlock($xor);
  939. $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor;
  940. }
  941. $key = $xor;
  942. }
  943. if($this->continuousBuffer){
  944. $this->decryptIV = $xor;
  945. if($start = strlen($ciphertext) % $block_size){
  946. $buffer['xor'] = substr($key, $start) . $buffer['xor'];
  947. }
  948. }
  949. break;
  950. case CRYPT_MODE_STREAM:
  951. $plaintext = $this->_decryptBlock($ciphertext);
  952. break;
  953. }
  954. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  955. }
  956. /**
  957. * Pad "packets".
  958. *
  959. * Block ciphers working by encrypting between their specified [$this->]block_size at a time
  960. * If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to
  961. * pad the input so that it is of the proper length.
  962. *
  963. * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH,
  964. * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
  965. * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
  966. * transmitted separately)
  967. *
  968. * @see Base::disablePadding()
  969. * @access public
  970. */
  971. public function enablePadding(){
  972. $this->padding = true;
  973. }
  974. /**
  975. * Do not pad packets.
  976. *
  977. * @see Base::enablePadding()
  978. * @access public
  979. */
  980. public function disablePadding(){
  981. $this->padding = false;
  982. }
  983. /**
  984. * Treat consecutive "packets" as if they are a continuous buffer.
  985. *
  986. * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets
  987. * will yield different outputs:
  988. *
  989. * <code>
  990. * echo $rijndael->encrypt(substr($plaintext, 0, 16));
  991. * echo $rijndael->encrypt(substr($plaintext, 16, 16));
  992. * </code>
  993. * <code>
  994. * echo $rijndael->encrypt($plaintext);
  995. * </code>
  996. *
  997. * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
  998. * another, as demonstrated with the following:
  999. *
  1000. * <code>
  1001. * $rijndael->encrypt(substr($plaintext, 0, 16));
  1002. * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
  1003. * </code>
  1004. * <code>
  1005. * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
  1006. * </code>
  1007. *
  1008. * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
  1009. * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
  1010. * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
  1011. *
  1012. * Put another way, when the continuous buffer is enabled, the state of the Crypt_*() object changes after each
  1013. * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
  1014. * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
  1015. * however, they are also less intuitive and more likely to cause you problems.
  1016. *
  1017. * Note: Could, but not must, extend by the child Crypt_* class
  1018. *
  1019. * @see Base::disableContinuousBuffer()
  1020. * @access public
  1021. */
  1022. public function enableContinuousBuffer(){
  1023. if($this->mode == CRYPT_MODE_ECB){
  1024. return;
  1025. }
  1026. $this->continuousBuffer = true;
  1027. }
  1028. /**
  1029. * Treat consecutive packets as if they are a discontinuous buffer.
  1030. *
  1031. * The default behavior.
  1032. *
  1033. * Note: Could, but not must, extend by the child Crypt_* class
  1034. *
  1035. * @see Base::enableContinuousBuffer()
  1036. * @access public
  1037. */
  1038. public function disableContinuousBuffer(){
  1039. if($this->mode == CRYPT_MODE_ECB){
  1040. return;
  1041. }
  1042. if(!$this->continuousBuffer){
  1043. return;
  1044. }
  1045. $this->continuousBuffer = false;
  1046. $this->changed = true;
  1047. }
  1048. /**
  1049. * Encrypts a block
  1050. *
  1051. * Note: Must extend by the child Crypt_* class
  1052. *
  1053. * @access private
  1054. * @param String $in
  1055. * @return String
  1056. */
  1057. protected function _encryptBlock($in){
  1058. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1059. }
  1060. /**
  1061. * Decrypts a block
  1062. *
  1063. * Note: Must extend by the child Crypt_* class
  1064. *
  1065. * @access private
  1066. * @param String $in
  1067. * @return String
  1068. */
  1069. protected function _decryptBlock($in){
  1070. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1071. }
  1072. /**
  1073. * Setup the key (expansion)
  1074. *
  1075. * Only used if $engine == CRYPT_MODE_INTERNAL
  1076. *
  1077. * Note: Must extend by the child Crypt_* class
  1078. *
  1079. * @see Base::_setup()
  1080. * @access private
  1081. */
  1082. protected function _setupKey(){
  1083. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1084. }
  1085. /**
  1086. * Setup the CRYPT_MODE_INTERNAL $engine
  1087. *
  1088. * (re)init, if necessary, the internal cipher $engine and flush all $buffers
  1089. * Used (only) if $engine == CRYPT_MODE_INTERNAL
  1090. *
  1091. * _setup() will be called each time if $changed === true
  1092. * typically this happens when using one or more of following public methods:
  1093. *
  1094. * - setKey()
  1095. *
  1096. * - setIV()
  1097. *
  1098. * - disableContinuousBuffer()
  1099. *
  1100. * - First run of encrypt() / decrypt() with no init-settings
  1101. *
  1102. * Internally: _setup() is called always before(!) en/decryption.
  1103. *
  1104. * Note: Could, but not must, extend by the child Crypt_* class
  1105. *
  1106. * @see setKey()
  1107. * @see setIV()
  1108. * @see disableContinuousBuffer()
  1109. * @access private
  1110. */
  1111. private function _setup(){
  1112. $this->_clearBuffers();
  1113. $this->_setupKey();
  1114. if($this->use_inline_crypt){
  1115. $this->_setupInlineCrypt();
  1116. }
  1117. }
  1118. /**
  1119. * Setup the CRYPT_MODE_MCRYPT $engine
  1120. *
  1121. * (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers
  1122. * Used (only) if $engine = CRYPT_MODE_MCRYPT
  1123. *
  1124. * _setupMcrypt() will be called each time if $changed === true
  1125. * typically this happens when using one or more of following public methods:
  1126. *
  1127. * - setKey()
  1128. *
  1129. * - setIV()
  1130. *
  1131. * - disableContinuousBuffer()
  1132. *
  1133. * - First run of encrypt() / decrypt()
  1134. *
  1135. *
  1136. * Note: Could, but not must, extend by the child Crypt_* class
  1137. *
  1138. * @see setKey()
  1139. * @see setIV()
  1140. * @see disableContinuousBuffer()
  1141. * @access private
  1142. */
  1143. private function _setupMcrypt(){
  1144. $this->_clearBuffers();
  1145. $this->enchanged = $this->dechanged = true;
  1146. if(!isset($this->enmcrypt)){
  1147. static $mcrypt_modes = array(
  1148. CRYPT_MODE_CTR => 'ctr',
  1149. CRYPT_MODE_ECB => MCRYPT_MODE_ECB,
  1150. CRYPT_MODE_CBC => MCRYPT_MODE_CBC,
  1151. CRYPT_MODE_CFB => 'ncfb',
  1152. CRYPT_MODE_OFB => MCRYPT_MODE_NOFB,
  1153. CRYPT_MODE_STREAM => MCRYPT_MODE_STREAM,
  1154. );
  1155. echo $this->cipher_name_mcrypt;
  1156. $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
  1157. $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
  1158. // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
  1159. // to workaround mcrypt's broken ncfb implementation in buffered mode
  1160. // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
  1161. if($this->mode == CRYPT_MODE_CFB){
  1162. $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
  1163. }
  1164. } // else should mcrypt_generic_deinit be called?
  1165. if($this->mode == CRYPT_MODE_CFB){
  1166. mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
  1167. }
  1168. }
  1169. /**
  1170. * Pads a string
  1171. *
  1172. * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize.
  1173. * $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to
  1174. * chr($this->block_size - (strlen($text) % $this->block_size)
  1175. *
  1176. * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
  1177. * and padding will, hence forth, be enabled.
  1178. *
  1179. * @see Base::_unpad()
  1180. * @param String $text
  1181. * @access private
  1182. * @return String
  1183. */
  1184. private function _pad($text){
  1185. $length = strlen($text);
  1186. if(!$this->padding){
  1187. if($length % $this->block_size == 0){
  1188. return $text;
  1189. }else{
  1190. user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})");
  1191. $this->padding = true;
  1192. }
  1193. }
  1194. $pad = $this->block_size - ($length % $this->block_size);
  1195. return str_pad($text, $length + $pad, chr($pad));
  1196. }
  1197. /**
  1198. * Unpads a string.
  1199. *
  1200. * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
  1201. * and false will be returned.
  1202. *
  1203. * @see Base::_pad()
  1204. * @param String $text
  1205. * @access private
  1206. * @return String
  1207. */
  1208. private function _unpad($text){
  1209. if(!$this->padding){
  1210. return $text;
  1211. }
  1212. $length = ord($text[strlen($text) - 1]);
  1213. if(!$length || $length > $this->block_size){
  1214. return false;
  1215. }
  1216. return substr($text, 0, -$length);
  1217. }
  1218. /**
  1219. * Clears internal buffers
  1220. *
  1221. * Clearing/resetting the internal buffers is done everytime
  1222. * after disableContinuousBuffer() or on cipher $engine (re)init
  1223. * ie after setKey() or setIV()
  1224. *
  1225. * Note: Could, but not must, extend by the child Crypt_* class
  1226. *
  1227. * @access public
  1228. */
  1229. private function _clearBuffers(){
  1230. $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
  1231. $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
  1232. // mcrypt's handling of invalid's $iv:
  1233. // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size);
  1234. $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0");
  1235. }
  1236. /**
  1237. * String Shift
  1238. *
  1239. * Inspired by array_shift
  1240. *
  1241. * @param String $string
  1242. * @param optional Integer $index
  1243. * @access private
  1244. * @return String
  1245. */
  1246. private function _stringShift(&$string, $index = 1){
  1247. $substr = substr($string, 0, $index);
  1248. $string = substr($string, $index);
  1249. return $substr;
  1250. }
  1251. /**
  1252. * Generate CTR XOR encryption key
  1253. *
  1254. * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
  1255. * plaintext / ciphertext in CTR mode.
  1256. *
  1257. * @see Base::decrypt()
  1258. * @see Base::encrypt()
  1259. * @param String $iv
  1260. * @param Integer $length
  1261. * @access private
  1262. * @return String $xor
  1263. */
  1264. private function _generateXor(&$iv, $length){
  1265. $xor = '';
  1266. $block_size = $this->block_size;
  1267. $num_blocks = floor(($length + ($block_size - 1)) / $block_size);
  1268. for($i = 0; $i < $num_blocks; $i++){
  1269. $xor.= $iv;
  1270. for($j = 4; $j <= $block_size; $j+= 4){
  1271. $temp = substr($iv, -$j, 4);
  1272. switch($temp){
  1273. case "\xFF\xFF\xFF\xFF":
  1274. $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
  1275. break;
  1276. case "\x7F\xFF\xFF\xFF":
  1277. $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
  1278. break 2;
  1279. default:
  1280. extract(unpack('Ncount', $temp));
  1281. $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
  1282. break 2;
  1283. }
  1284. }
  1285. }
  1286. return $xor;
  1287. }
  1288. /**
  1289. * Setup the performance-optimized function for de/encrypt()
  1290. *
  1291. * Stores the created (or existing) callback function-name
  1292. * in $this->inline_crypt
  1293. *
  1294. * Internally for phpseclib developers:
  1295. *
  1296. * _setupInlineCrypt() would be called only if:
  1297. *
  1298. * - $engine == CRYPT_MODE_INTERNAL and
  1299. *
  1300. * - $use_inline_crypt === true
  1301. *
  1302. * - each time on _setup(), after(!) _setupKey()
  1303. *
  1304. *
  1305. * This ensures that _setupInlineCrypt() has always a
  1306. * full ready2go initializated internal cipher $engine state
  1307. * where, for example, the keys allready expanded,
  1308. * keys/block_size calculated and such.
  1309. *
  1310. * It is, each time if called, the responsibility of _setupInlineCrypt():
  1311. *
  1312. * - to set $this->inline_crypt to a valid and fully working callback function
  1313. * as a (faster) replacement for encrypt() / decrypt()
  1314. *
  1315. * - NOT to create unlimited callback functions (for memory reasons!)
  1316. * no matter how often _setupInlineCrypt() would be called. At some
  1317. * point of amount they must be generic re-useable.
  1318. *
  1319. * - the code of _setupInlineCrypt() it self,
  1320. * and the generated callback code,
  1321. * must be, in following order:
  1322. * - 100% safe
  1323. * - 100% compatible to encrypt()/decrypt()
  1324. * - using only php5+ features/lang-constructs/php-extensions if
  1325. * compatibility (down to php4) or fallback is provided
  1326. * - readable/maintainable/understandable/commented and... not-cryptic-styled-code :-)
  1327. * - >= 10% faster than encrypt()/decrypt() [which is, by the way,
  1328. * the reason for the existence of _setupInlineCrypt() :-)]
  1329. * - memory-nice
  1330. * - short (as good as possible)
  1331. *
  1332. * Note: - _setupInlineCrypt() is using _createInlineCryptFunction() to create the full callback function code.
  1333. * - In case of using inline crypting, _setupInlineCrypt() must extend by the child Crypt_* class.
  1334. * - The following variable names are reserved:
  1335. * - $_* (all variable names prefixed with an underscore)
  1336. * - $self (object reference to it self. Do not use $this, but $self instead)
  1337. * - $in (the content of $in has to en/decrypt by the generated code)
  1338. * - The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only
  1339. *
  1340. *
  1341. * @see Base::_setup()
  1342. * @see Base::_createInlineCryptFunction()
  1343. * @see Base::encrypt()
  1344. * @see Base::decrypt()
  1345. * @access private
  1346. */
  1347. private function _setupInlineCrypt(){
  1348. // If a Crypt_* class providing inline crypting it must extend _setupInlineCrypt()
  1349. // If, for any reason, an extending Base() Crypt_* class
  1350. // not using inline crypting then it must be ensured that: $this->use_inline_crypt = false
  1351. // ie in the class var declaration of $use_inline_crypt in general for the Crypt_* class,
  1352. // in the constructor at object instance-time
  1353. // or, if it's runtime-specific, at runtime
  1354. $this->use_inline_crypt = false;
  1355. }
  1356. /**
  1357. * Creates the performance-optimized function for en/decrypt()
  1358. *
  1359. * Internally for phpseclib developers:
  1360. *
  1361. * _createInlineCryptFunction():
  1362. *
  1363. * - merge the $cipher_code [setup'ed by _setupInlineCrypt()]
  1364. * with the current [$this->]mode of operation code
  1365. *
  1366. * - create the $inline function, which called by encrypt() / decrypt()
  1367. * as its replacement to speed up the en/decryption operations.
  1368. *
  1369. * - return the name of the created $inline callback function
  1370. *
  1371. * - used to speed up en/decryption
  1372. *
  1373. *
  1374. *
  1375. * The main reason why can speed up things [up to 50%] this way are:
  1376. *
  1377. * - using variables more effective then regular.
  1378. * (ie no use of expensive arrays but integers $k_0, $k_1 ...
  1379. * or even, for example, the pure $key[] values hardcoded)
  1380. *
  1381. * - avoiding 1000's of function calls of ie _encryptBlock()
  1382. * but inlining the crypt operations.
  1383. * in the mode of operation for() loop.
  1384. *
  1385. * - full loop unroll the (sometimes key-dependent) rounds
  1386. * avoiding this way ++$i counters and runtime-if's etc...
  1387. *
  1388. * The basic code architectur of the generated $inline en/decrypt()
  1389. * lambda function, in pseudo php, is:
  1390. *
  1391. * <code>
  1392. * +----------------------------------------------------------------------------------------------+
  1393. * | callback $inline = create_function: |
  1394. * | lambda_function_0001_crypt_ECB($action, $text) |
  1395. * | { |
  1396. * | INSERT PHP CODE OF: |
  1397. * | $cipher_code['init_crypt']; // general init code. |
  1398. * | // ie: $sbox'es declarations used for |
  1399. * | // encrypt and decrypt'ing. |
  1400. * | |
  1401. * | switch ($action) { |
  1402. * | case 'encrypt': |
  1403. * | INSERT PHP CODE OF: |
  1404. * | $cipher_code['init_encrypt']; // encrypt sepcific init code. |
  1405. * | ie: specified $key or $box |
  1406. * | declarations for encrypt'ing. |
  1407. * | |
  1408. * | foreach ($ciphertext) { |
  1409. * | $in = $block_size of $ciphertext; |
  1410. * | |
  1411. * | INSERT PHP CODE OF: |
  1412. * | $cipher_code['encrypt_block']; // encrypt's (string) $in, which is always: |
  1413. * | // strlen($in) == $this->block_size |
  1414. * | // here comes the cipher algorithm in action |
  1415. * | // for encryption. |
  1416. * | // $cipher_code['encrypt_block'] has to |
  1417. * | // encrypt the content of the $in variable |
  1418. * | |
  1419. * | $plaintext .= $in; |
  1420. * | } |
  1421. * | return $plaintext; |
  1422. * | |
  1423. * | case 'decrypt': |
  1424. * | INSERT PHP CODE OF: |
  1425. * | $cipher_code['init_decrypt']; // decrypt sepcific init code |
  1426. * | ie: specified $key or $box |
  1427. * | declarations for decrypt'ing. |
  1428. * | foreach ($plaintext) { |
  1429. * | $in = $block_size of $plaintext; |
  1430. * | |
  1431. * | INSERT PHP CODE OF: |
  1432. * | $cipher_code['decrypt_block']; // decrypt's (string) $in, which is always |
  1433. * | // strlen($in) == $this->block_size |
  1434. * | // here comes the cipher algorithm in action |
  1435. * | // for decryption. |
  1436. * | // $cipher_code['decrypt_block'] has to |
  1437. * | // decrypt the content of the $in variable |
  1438. * | $ciphertext .= $in; |
  1439. * | } |
  1440. * | return $ciphertext; |
  1441. * | } |
  1442. * | } |
  1443. * +----------------------------------------------------------------------------------------------+
  1444. * </code>
  1445. *
  1446. * See also the Crypt_*::_setupInlineCrypt()'s for
  1447. * productive inline $cipher_code's how they works.
  1448. *
  1449. * Structure of:
  1450. * <code>
  1451. * $cipher_code = array(
  1452. * 'init_crypt' => (string) '', // optional
  1453. * 'init_encrypt' => (string) '', // optional
  1454. * 'init_decrypt' => (string) '', // optional
  1455. * 'encrypt_block' => (string) '', // required
  1456. * 'decrypt_block' => (string) '' // required
  1457. * );
  1458. * </code>
  1459. *
  1460. * @see Base::_setupInlineCrypt()
  1461. * @see Base::encrypt()
  1462. * @see Base::decrypt()
  1463. * @param Array $cipher_code
  1464. * @access private
  1465. * @return String (the name of the created callback function)
  1466. */
  1467. private function _createInlineCryptFunction($cipher_code){
  1468. $block_size = $this->block_size;
  1469. // optional
  1470. $init_crypt = isset($cipher_code['init_crypt']) ? $cipher_code['init_crypt'] : '';
  1471. $init_encrypt = isset($cipher_code['init_encrypt']) ? $cipher_code['init_encrypt'] : '';
  1472. $init_decrypt = isset($cipher_code['init_decrypt']) ? $cipher_code['init_decrypt'] : '';
  1473. // required
  1474. $encrypt_block = $cipher_code['encrypt_block'];
  1475. $decrypt_block = $cipher_code['decrypt_block'];
  1476. // Generating mode of operation inline code,
  1477. // merged with the $cipher_code algorithm
  1478. // for encrypt- and decryption.
  1479. switch($this->mode){
  1480. case CRYPT_MODE_ECB:
  1481. $encrypt = $init_encrypt . '
  1482. $_ciphertext = "";
  1483. $_text = $self->_pad($_text);
  1484. $_plaintext_len = strlen($_text);
  1485. for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
  1486. $in = substr($_text, $_i, ' . $block_size . ');
  1487. ' . $encrypt_block . '
  1488. $_ciphertext.= $in;
  1489. }
  1490. return $_ciphertext;
  1491. ';
  1492. $decrypt = $init_decrypt . '
  1493. $_plaintext = "";
  1494. $_text = str_pad($_text, strlen($_text) + (' . $block_size . ' - strlen($_text) % ' . $block_size . ') % ' . $block_size . ', chr(0));
  1495. $_ciphertext_len = strlen($_text);
  1496. for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
  1497. $in = substr($_text, $_i, ' . $block_size . ');
  1498. ' . $decrypt_block . '
  1499. $_plaintext.= $in;
  1500. }
  1501. return $self->_unpad($_plaintext);
  1502. ';
  1503. break;
  1504. case CRYPT_MODE_CTR:
  1505. $encrypt = $init_encrypt . '
  1506. $_ciphertext = "";
  1507. $_plaintext_len = strlen($_text);
  1508. $_xor = $self->encryptIV;
  1509. $_buffer = &$self->enbuffer;
  1510. if (strlen($_buffer["encrypted"])) {
  1511. for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
  1512. $_block = substr($_text, $_i, ' . $block_size . ');
  1513. if (strlen($_block) > strlen($_buffer["encrypted"])) {
  1514. $in = $self->_generateXor($_xor, ' . $block_size . ');
  1515. ' . $encrypt_block . '
  1516. $_buffer["encrypted"].= $in;
  1517. }
  1518. $_key = $self->_stringShift($_buffer["encrypted"], ' . $block_size . ');
  1519. $_ciphertext.= $_block ^ $_key;
  1520. }
  1521. } else {
  1522. for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
  1523. $_block = substr($_text, $_i, ' . $block_size . ');
  1524. $in = $self->_generateXor($_xor, ' . $block_size . ');
  1525. ' . $encrypt_block . '
  1526. $_key = $in;
  1527. $_ciphertext.= $_block ^ $_key;
  1528. }
  1529. }
  1530. if ($self->continuousBuffer) {
  1531. $self->encryptIV = $_xor;
  1532. if ($_start = $_plaintext_len % ' . $block_size . ') {
  1533. $_buffer["encrypted"] = substr($_key, $_start) . $_buffer["encrypted"];
  1534. }
  1535. }
  1536. return $_ciphertext;
  1537. ';
  1538. $decrypt = $init_encrypt . '
  1539. $_plaintext = "";
  1540. $_ciphertext_len = strlen($_text);
  1541. $_xor = $self->decryptIV;
  1542. $_buffer = &$self->debuffer;
  1543. if (strlen($_buffer["ciphertext"])) {
  1544. for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
  1545. $_block = substr($_text, $_i, ' . $block_size . ');
  1546. if (strlen($_block) > strlen($_buffer["ciphertext"])) {
  1547. $in = $self->_generateXor($_xor, ' . $block_size . ');
  1548. ' . $encrypt_block . '
  1549. $_buffer["ciphertext"].= $in;
  1550. }
  1551. $_key = $self->_stringShift($_buffer["ciphertext"], ' . $block_size . ');
  1552. $_plaintext.= $_block ^ $_key;
  1553. }
  1554. } else {
  1555. for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
  1556. $_block = substr($_text, $_i, ' . $block_size . ');
  1557. $in = $self->_generateXor($_xor, ' . $block_size . ');
  1558. ' . $encrypt_block . '
  1559. $_key = $in;
  1560. $_plaintext.= $_block ^ $_key;
  1561. }
  1562. }
  1563. if ($self->continuousBuffer) {
  1564. $self->decryptIV = $_xor;
  1565. if ($_start = $_ciphertext_len % ' . $block_size . ') {
  1566. $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
  1567. }
  1568. }
  1569. return $_plaintext;
  1570. ';
  1571. break;
  1572. case CRYPT_MODE_CFB:
  1573. $encrypt = $init_encrypt . '
  1574. $_ciphertext = "";
  1575. $_buffer = &$self->enbuffer;
  1576. if ($self->continuousBuffer) {
  1577. $_iv = &$self->encryptIV;
  1578. $_pos = &$_buffer["pos"];
  1579. } else {
  1580. $_iv = $self->encryptIV;
  1581. $_pos = 0;
  1582. }
  1583. $_len = strlen($_text);
  1584. $_i = 0;
  1585. if ($_pos) {
  1586. $_orig_pos = $_pos;
  1587. $_max = ' . $block_size . ' - $_pos;
  1588. if ($_len >= $_max) {
  1589. $_i = $_max;
  1590. $_len-= $_max;
  1591. $_pos = 0;
  1592. } else {
  1593. $_i = $_len;
  1594. $_pos+= $_len;
  1595. $_len = 0;
  1596. }
  1597. $_ciphertext = substr($_iv, $_orig_pos) ^ $_text;
  1598. $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i);
  1599. }
  1600. while ($_len >= ' . $block_size . ') {
  1601. $in = $_iv;
  1602. ' . $encrypt_block . ';
  1603. $_iv = $in ^ substr($_text, $_i, ' . $block_size . ');
  1604. $_ciphertext.= $_iv;
  1605. $_len-= ' . $block_size . ';
  1606. $_i+= ' . $block_size . ';
  1607. }
  1608. if ($_len) {
  1609. $in = $_iv;
  1610. ' . $encrypt_block . '
  1611. $_iv = $in;
  1612. $_block = $_iv ^ substr($_text, $_i);
  1613. $_iv = substr_replace($_iv, $_block, 0, $_len);
  1614. $_ciphertext.= $_block;
  1615. $_pos = $_len;
  1616. }
  1617. return $_ciphertext;
  1618. ';
  1619. $decrypt = $init_encrypt . '
  1620. $_plaintext = "";
  1621. $_buffer = &$self->debuffer;
  1622. if ($self->continuousBuffer) {
  1623. $_iv = &$self->decryptIV;
  1624. $_pos = &$_buffer["pos"];
  1625. } else {
  1626. $_iv = $self->decryptIV;
  1627. $_pos = 0;
  1628. }
  1629. $_len = strlen($_text);
  1630. $_i = 0;
  1631. if ($_pos) {
  1632. $_orig_pos = $_pos;
  1633. $_max = ' . $block_size . ' - $_pos;
  1634. if ($_len >= $_max) {
  1635. $_i = $_max;
  1636. $_len-= $_max;
  1637. $_pos = 0;
  1638. } else {
  1639. $_i = $_len;
  1640. $_pos+= $_len;
  1641. $_len = 0;
  1642. }
  1643. $_plaintext = substr($_iv, $_orig_pos) ^ $_text;
  1644. $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i);
  1645. }
  1646. while ($_len >= ' . $block_size . ') {
  1647. $in = $_iv;
  1648. ' . $encrypt_block . '
  1649. $_iv = $in;
  1650. $cb = substr($_text, $_i, ' . $block_size . ');
  1651. $_plaintext.= $_iv ^ $cb;
  1652. $_iv = $cb;
  1653. $_len-= ' . $block_size . ';
  1654. $_i+= ' . $block_size . ';
  1655. }
  1656. if ($_len) {
  1657. $in = $_iv;
  1658. ' . $encrypt_block . '
  1659. $_iv = $in;
  1660. $_plaintext.= $_iv ^ substr($_text, $_i);
  1661. $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len);
  1662. $_pos = $_len;
  1663. }
  1664. return $_plaintext;
  1665. ';
  1666. break;
  1667. case CRYPT_MODE_OFB:
  1668. $encrypt = $init_encrypt . '
  1669. $_ciphertext = "";
  1670. $_plaintext_len = strlen($_text);
  1671. $_xor = $self->encryptIV;
  1672. $_buffer = &$self->enbuffer;
  1673. if (strlen($_buffer["xor"])) {
  1674. for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
  1675. $_block = substr($_text, $_i, ' . $block_size . ');
  1676. if (strlen($_block) > strlen($_buffer["xor"])) {
  1677. $in = $_xor;
  1678. ' . $encrypt_block . '
  1679. $_xor = $in;
  1680. $_buffer["xor"].= $_xor;
  1681. }
  1682. $_key = $self->_stringShift($_buffer["xor"], ' . $block_size . ');
  1683. $_ciphertext.= $_block ^ $_key;
  1684. }
  1685. } else {
  1686. for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
  1687. $in = $_xor;
  1688. ' . $encrypt_block . '
  1689. $_xor = $in;
  1690. $_ciphertext.= substr($_text, $_i, ' . $block_size . ') ^ $_xor;
  1691. }
  1692. $_key = $_xor;
  1693. }
  1694. if ($self->continuousBuffer) {
  1695. $self->encryptIV = $_xor;
  1696. if ($_start = $_plaintext_len % ' . $block_size . ') {
  1697. $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
  1698. }
  1699. }
  1700. return $_ciphertext;
  1701. ';
  1702. $decrypt = $init_encrypt . '
  1703. $_plaintext = "";
  1704. $_ciphertext_len = strlen($_text);
  1705. $_xor = $self->decryptIV;
  1706. $_buffer = &$self->debuffer;
  1707. if (strlen($_buffer["xor"])) {
  1708. for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
  1709. $_block = substr($_text, $_i, ' . $block_size . ');
  1710. if (strlen($_block) > strlen($_buffer["xor"])) {
  1711. $in = $_xor;
  1712. ' . $encrypt_block . '
  1713. $_xor = $in;
  1714. $_buffer["xor"].= $_xor;
  1715. }
  1716. $_key = $self->_stringShift($_buffer["xor"], ' . $block_size . ');
  1717. $_plaintext.= $_block ^ $_key;
  1718. }
  1719. } else {
  1720. for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
  1721. $in = $_xor;
  1722. ' . $encrypt_block . '
  1723. $_xor = $in;
  1724. $_plaintext.= substr($_text, $_i, ' . $block_size . ') ^ $_xor;
  1725. }
  1726. $_key = $_xor;
  1727. }
  1728. if ($self->continuousBuffer) {
  1729. $self->decryptIV = $_xor;
  1730. if ($_start = $_ciphertext_len % ' . $block_size . ') {
  1731. $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
  1732. }
  1733. }
  1734. return $_plaintext;
  1735. ';
  1736. break;
  1737. case CRYPT_MODE_STREAM:
  1738. $encrypt = $init_encrypt . '
  1739. $_ciphertext = "";
  1740. ' . $encrypt_block . '
  1741. return $_ciphertext;
  1742. ';
  1743. $decrypt = $init_decrypt . '
  1744. $_plaintext = "";
  1745. ' . $decrypt_block . '
  1746. return $_plaintext;
  1747. ';
  1748. break;
  1749. // case CRYPT_MODE_CBC:
  1750. default:
  1751. $encrypt = $init_encrypt . '
  1752. $_ciphertext = "";
  1753. $_text = $self->_pad($_text);
  1754. $_plaintext_len = strlen($_text);
  1755. $in = $self->encryptIV;
  1756. for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
  1757. $in = substr($_text, $_i, ' . $block_size . ') ^ $in;
  1758. ' . $encrypt_block . '
  1759. $_ciphertext.= $in;
  1760. }
  1761. if ($self->continuousBuffer) {
  1762. $self->encryptIV = $in;
  1763. }
  1764. return $_ciphertext;
  1765. ';
  1766. $decrypt = $init_decrypt . '
  1767. $_plaintext = "";
  1768. $_text = str_pad($_text, strlen($_text) + (' . $block_size . ' - strlen($_text) % ' . $block_size . ') % ' . $block_size . ', chr(0));
  1769. $_ciphertext_len = strlen($_text);
  1770. $_iv = $self->decryptIV;
  1771. for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
  1772. $in = $_block = substr($_text, $_i, ' . $block_size . ');
  1773. ' . $decrypt_block . '
  1774. $_plaintext.= $in ^ $_iv;
  1775. $_iv = $_block;
  1776. }
  1777. if ($self->continuousBuffer) {
  1778. $self->decryptIV = $_iv;
  1779. }
  1780. return $self->_unpad($_plaintext);
  1781. ';
  1782. break;
  1783. }
  1784. // Create the $inline function and return its name as string. Ready to run!
  1785. return create_function('$_action, &$self, $_text', $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }');
  1786. }
  1787. /**
  1788. * Holds the lambda_functions table (classwide)
  1789. *
  1790. * Each name of the lambda function, created from
  1791. * _setupInlineCrypt() && _createInlineCryptFunction()
  1792. * is stored, classwide (!), here for reusing.
  1793. *
  1794. * The string-based index of $function is a classwide
  1795. * uniqe value representing, at least, the $mode of
  1796. * operation (or more... depends of the optimizing level)
  1797. * for which $mode the lambda function was created.
  1798. *
  1799. * @access private
  1800. * @return &Array
  1801. */
  1802. private function &_getLambdaFunctions(){
  1803. static $functions = array();
  1804. return $functions;
  1805. }
  1806. }