TripleDES.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Pure-PHP implementation of Triple DES.
  5. *
  6. * Uses mcrypt, if available, and an internal implementation, otherwise. Operates in the EDE3 mode (encrypt-decrypt-encrypt).
  7. *
  8. * PHP versions 4 and 5
  9. *
  10. * Here's a short example of how to use this library:
  11. * <code>
  12. * <?php
  13. * include('Crypt/TripleDES.php');
  14. *
  15. * $des = new Crypt_TripleDES();
  16. *
  17. * $des->setKey('abcdefghijklmnopqrstuvwx');
  18. *
  19. * $size = 10 * 1024;
  20. * $plaintext = '';
  21. * for ($i = 0; $i < $size; $i++) {
  22. * $plaintext.= 'a';
  23. * }
  24. *
  25. * echo $des->decrypt($des->encrypt($plaintext));
  26. * ?>
  27. * </code>
  28. *
  29. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  30. * of this software and associated documentation files (the "Software"), to deal
  31. * in the Software without restriction, including without limitation the rights
  32. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  33. * copies of the Software, and to permit persons to whom the Software is
  34. * furnished to do so, subject to the following conditions:
  35. *
  36. * The above copyright notice and this permission notice shall be included in
  37. * all copies or substantial portions of the Software.
  38. *
  39. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  42. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  43. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  44. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  45. * THE SOFTWARE.
  46. *
  47. * @category Crypt
  48. * @package Crypt_TripleDES
  49. * @author Jim Wigginton <terrafrost@php.net>
  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. * Include Crypt_DES
  56. */
  57. if (!class_exists('Crypt_DES')) {
  58. require_once('DES.php');
  59. }
  60. /**
  61. * Encrypt / decrypt using inner chaining
  62. *
  63. * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3).
  64. */
  65. define('CRYPT_DES_MODE_3CBC', -2);
  66. /**
  67. * Encrypt / decrypt using outer chaining
  68. *
  69. * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC.
  70. */
  71. define('CRYPT_DES_MODE_CBC3', CRYPT_DES_MODE_CBC);
  72. /**
  73. * Pure-PHP implementation of Triple DES.
  74. *
  75. * @author Jim Wigginton <terrafrost@php.net>
  76. * @version 0.1.0
  77. * @access public
  78. * @package Crypt_TerraDES
  79. */
  80. class Crypt_TripleDES extends Crypt_DES {
  81. /**
  82. * The Crypt_DES objects
  83. *
  84. * @var Array
  85. * @access private
  86. */
  87. var $des;
  88. /**
  89. * Default Constructor.
  90. *
  91. * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be
  92. * CRYPT_DES_MODE_ECB or CRYPT_DES_MODE_CBC. If not explictly set, CRYPT_DES_MODE_CBC will be used.
  93. *
  94. * @param optional Integer $mode
  95. * @return Crypt_TripleDES
  96. * @access public
  97. */
  98. function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC)
  99. {
  100. if ( !defined('CRYPT_DES_MODE') ) {
  101. switch (true) {
  102. case extension_loaded('mcrypt') && in_array('tripledes', mcrypt_list_algorithms()):
  103. define('CRYPT_DES_MODE', CRYPT_DES_MODE_MCRYPT);
  104. break;
  105. default:
  106. define('CRYPT_DES_MODE', CRYPT_DES_MODE_INTERNAL);
  107. }
  108. }
  109. if ( $mode == CRYPT_DES_MODE_3CBC ) {
  110. $this->mode = CRYPT_DES_MODE_3CBC;
  111. $this->des = array(
  112. new Crypt_DES(CRYPT_DES_MODE_CBC),
  113. new Crypt_DES(CRYPT_DES_MODE_CBC),
  114. new Crypt_DES(CRYPT_DES_MODE_CBC)
  115. );
  116. $this->paddable = true;
  117. // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
  118. $this->des[0]->disablePadding();
  119. $this->des[1]->disablePadding();
  120. $this->des[2]->disablePadding();
  121. return;
  122. }
  123. switch ( CRYPT_DES_MODE ) {
  124. case CRYPT_DES_MODE_MCRYPT:
  125. switch ($mode) {
  126. case CRYPT_DES_MODE_ECB:
  127. $this->paddable = true;
  128. $this->mode = MCRYPT_MODE_ECB;
  129. break;
  130. case CRYPT_DES_MODE_CTR:
  131. $this->mode = 'ctr';
  132. break;
  133. case CRYPT_DES_MODE_CFB:
  134. $this->mode = 'ncfb';
  135. $this->ecb = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
  136. break;
  137. case CRYPT_DES_MODE_OFB:
  138. $this->mode = MCRYPT_MODE_NOFB;
  139. break;
  140. case CRYPT_DES_MODE_CBC:
  141. default:
  142. $this->paddable = true;
  143. $this->mode = MCRYPT_MODE_CBC;
  144. }
  145. $this->enmcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
  146. $this->demcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
  147. break;
  148. default:
  149. $this->des = array(
  150. new Crypt_DES(CRYPT_DES_MODE_ECB),
  151. new Crypt_DES(CRYPT_DES_MODE_ECB),
  152. new Crypt_DES(CRYPT_DES_MODE_ECB)
  153. );
  154. // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
  155. $this->des[0]->disablePadding();
  156. $this->des[1]->disablePadding();
  157. $this->des[2]->disablePadding();
  158. switch ($mode) {
  159. case CRYPT_DES_MODE_ECB:
  160. case CRYPT_DES_MODE_CBC:
  161. $this->paddable = true;
  162. $this->mode = $mode;
  163. break;
  164. case CRYPT_DES_MODE_CTR:
  165. case CRYPT_DES_MODE_CFB:
  166. case CRYPT_DES_MODE_OFB:
  167. $this->mode = $mode;
  168. break;
  169. default:
  170. $this->paddable = true;
  171. $this->mode = CRYPT_DES_MODE_CBC;
  172. }
  173. if (function_exists('create_function') && is_callable('create_function')) {
  174. $this->inline_crypt_setup(3);
  175. $this->use_inline_crypt = true;
  176. }
  177. }
  178. }
  179. /**
  180. * Sets the key.
  181. *
  182. * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
  183. * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate.
  184. *
  185. * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
  186. *
  187. * If the key is not explicitly set, it'll be assumed to be all zero's.
  188. *
  189. * @access public
  190. * @param String $key
  191. */
  192. function setKey($key)
  193. {
  194. $length = strlen($key);
  195. if ($length > 8) {
  196. $key = str_pad($key, 24, chr(0));
  197. // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
  198. // http://php.net/function.mcrypt-encrypt#47973
  199. //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
  200. } else {
  201. $key = str_pad($key, 8, chr(0));
  202. }
  203. $this->key = $key;
  204. switch (true) {
  205. case CRYPT_DES_MODE == CRYPT_DES_MODE_INTERNAL:
  206. case $this->mode == CRYPT_DES_MODE_3CBC:
  207. $this->des[0]->setKey(substr($key, 0, 8));
  208. $this->des[1]->setKey(substr($key, 8, 8));
  209. $this->des[2]->setKey(substr($key, 16, 8));
  210. // Merge the three DES-1-dim-key-arrays for 3DES-inline-en/decrypting
  211. if ($this->use_inline_crypt && $this->mode != CRYPT_DES_MODE_3CBC) {
  212. $this->keys = array(
  213. CRYPT_DES_ENCRYPT_1DIM => array_merge(
  214. $this->des[0]->keys[CRYPT_DES_ENCRYPT_1DIM],
  215. $this->des[1]->keys[CRYPT_DES_DECRYPT_1DIM],
  216. $this->des[2]->keys[CRYPT_DES_ENCRYPT_1DIM]
  217. ),
  218. CRYPT_DES_DECRYPT_1DIM => array_merge(
  219. $this->des[2]->keys[CRYPT_DES_DECRYPT_1DIM],
  220. $this->des[1]->keys[CRYPT_DES_ENCRYPT_1DIM],
  221. $this->des[0]->keys[CRYPT_DES_DECRYPT_1DIM]
  222. ),
  223. );
  224. }
  225. }
  226. $this->enchanged = $this->dechanged = true;
  227. }
  228. /**
  229. * Sets the password.
  230. *
  231. * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
  232. * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
  233. * $hash, $salt, $method
  234. *
  235. * @param String $password
  236. * @param optional String $method
  237. * @access public
  238. */
  239. function setPassword($password, $method = 'pbkdf2')
  240. {
  241. $key = '';
  242. switch ($method) {
  243. default: // 'pbkdf2'
  244. list(, , $hash, $salt, $count) = func_get_args();
  245. if (!isset($hash)) {
  246. $hash = 'sha1';
  247. }
  248. // WPA and WPA2 use the SSID as the salt
  249. if (!isset($salt)) {
  250. $salt = 'phpseclib';
  251. }
  252. // RFC2898#section-4.2 uses 1,000 iterations by default
  253. // WPA and WPA2 use 4,096.
  254. if (!isset($count)) {
  255. $count = 1000;
  256. }
  257. if (!class_exists('Crypt_Hash')) {
  258. require_once('Crypt/Hash.php');
  259. }
  260. $i = 1;
  261. while (strlen($key) < 24) { // $dkLen == 24
  262. $hmac = new Crypt_Hash();
  263. $hmac->setHash($hash);
  264. $hmac->setKey($password);
  265. $f = $u = $hmac->hash($salt . pack('N', $i++));
  266. for ($j = 2; $j <= $count; $j++) {
  267. $u = $hmac->hash($u);
  268. $f^= $u;
  269. }
  270. $key.= $f;
  271. }
  272. }
  273. $this->setKey($key);
  274. }
  275. /**
  276. * Sets the initialization vector. (optional)
  277. *
  278. * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explictly set, it'll be assumed
  279. * to be all zero's.
  280. *
  281. * @access public
  282. * @param String $iv
  283. */
  284. function setIV($iv)
  285. {
  286. $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, 8), 8, chr(0));
  287. if ($this->mode == CRYPT_DES_MODE_3CBC) {
  288. $this->des[0]->setIV($iv);
  289. $this->des[1]->setIV($iv);
  290. $this->des[2]->setIV($iv);
  291. }
  292. $this->enchanged = $this->dechanged = true;
  293. }
  294. /**
  295. * Encrypts a message.
  296. *
  297. * @access public
  298. * @param String $plaintext
  299. */
  300. function encrypt($plaintext)
  301. {
  302. if ($this->paddable) {
  303. $plaintext = $this->_pad($plaintext);
  304. }
  305. // if the key is smaller then 8, do what we'd normally do
  306. if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
  307. $ciphertext = $this->des[2]->encrypt($this->des[1]->decrypt($this->des[0]->encrypt($plaintext)));
  308. return $ciphertext;
  309. }
  310. if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
  311. if ($this->enchanged) {
  312. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  313. if ($this->mode == 'ncfb') {
  314. mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
  315. }
  316. $this->enchanged = false;
  317. }
  318. if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
  319. $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
  320. } else {
  321. $iv = &$this->encryptIV;
  322. $pos = &$this->enbuffer['pos'];
  323. $len = strlen($plaintext);
  324. $ciphertext = '';
  325. $i = 0;
  326. if ($pos) {
  327. $orig_pos = $pos;
  328. $max = 8 - $pos;
  329. if ($len >= $max) {
  330. $i = $max;
  331. $len-= $max;
  332. $pos = 0;
  333. } else {
  334. $i = $len;
  335. $pos+= $len;
  336. $len = 0;
  337. }
  338. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  339. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  340. $this->enbuffer['enmcrypt_init'] = true;
  341. }
  342. if ($len >= 8) {
  343. if ($this->enbuffer['enmcrypt_init'] === false || $len > 950) {
  344. if ($this->enbuffer['enmcrypt_init'] === true) {
  345. mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
  346. $this->enbuffer['enmcrypt_init'] = false;
  347. }
  348. $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % 8));
  349. $iv = substr($ciphertext, -8);
  350. $i = strlen($ciphertext);
  351. $len%= 8;
  352. } else {
  353. while ($len >= 8) {
  354. $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, 8);
  355. $ciphertext.= $iv;
  356. $len-= 8;
  357. $i+= 8;
  358. }
  359. }
  360. }
  361. if ($len) {
  362. $iv = mcrypt_generic($this->ecb, $iv);
  363. $block = $iv ^ substr($plaintext, $i);
  364. $iv = substr_replace($iv, $block, 0, $len);
  365. $ciphertext.= $block;
  366. $pos = $len;
  367. }
  368. return $ciphertext;
  369. }
  370. if (!$this->continuousBuffer) {
  371. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  372. }
  373. return $ciphertext;
  374. }
  375. if (strlen($this->key) <= 8) {
  376. $this->des[0]->mode = $this->mode;
  377. return $this->des[0]->encrypt($plaintext);
  378. }
  379. if ($this->use_inline_crypt) {
  380. $inline = $this->inline_crypt;
  381. return $inline('encrypt', $this, $plaintext);
  382. }
  383. $des = $this->des;
  384. $buffer = &$this->enbuffer;
  385. $continuousBuffer = $this->continuousBuffer;
  386. $ciphertext = '';
  387. switch ($this->mode) {
  388. case CRYPT_DES_MODE_ECB:
  389. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  390. $block = substr($plaintext, $i, 8);
  391. // all of these _processBlock calls could, in theory, be put in a function - say Crypt_TripleDES::_ede_encrypt() or something.
  392. // only problem with that: it would slow encryption and decryption down. $this->des would have to be called every time that
  393. // function is called, instead of once for the whole string of text that's being encrypted, which would, in turn, make
  394. // encryption and decryption take more time, per this:
  395. //
  396. // http://blog.libssh2.org/index.php?/archives/21-Compiled-Variables.html
  397. $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
  398. $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
  399. $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
  400. $ciphertext.= $block;
  401. }
  402. break;
  403. case CRYPT_DES_MODE_CBC:
  404. $xor = $this->encryptIV;
  405. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  406. $block = substr($plaintext, $i, 8) ^ $xor;
  407. $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
  408. $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
  409. $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
  410. $xor = $block;
  411. $ciphertext.= $block;
  412. }
  413. if ($this->continuousBuffer) {
  414. $this->encryptIV = $xor;
  415. }
  416. break;
  417. case CRYPT_DES_MODE_CTR:
  418. $xor = $this->encryptIV;
  419. if (strlen($buffer['encrypted'])) {
  420. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  421. $block = substr($plaintext, $i, 8);
  422. if (strlen($block) > strlen($buffer['encrypted'])) {
  423. $key = $this->_generate_xor($xor);
  424. $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
  425. $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
  426. $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
  427. $buffer['encrypted'].= $key;
  428. }
  429. $key = $this->_string_shift($buffer['encrypted']);
  430. $ciphertext.= $block ^ $key;
  431. }
  432. } else {
  433. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  434. $block = substr($plaintext, $i, 8);
  435. $key = $this->_generate_xor($xor);
  436. $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
  437. $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
  438. $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
  439. $ciphertext.= $block ^ $key;
  440. }
  441. }
  442. if ($this->continuousBuffer) {
  443. $this->encryptIV = $xor;
  444. if ($start = strlen($plaintext) & 7) {
  445. $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
  446. }
  447. }
  448. break;
  449. case CRYPT_DES_MODE_CFB:
  450. if (strlen($buffer['xor'])) {
  451. $ciphertext = $plaintext ^ $buffer['xor'];
  452. $iv = $buffer['encrypted'] . $ciphertext;
  453. $start = strlen($ciphertext);
  454. $buffer['encrypted'].= $ciphertext;
  455. $buffer['xor'] = substr($buffer['xor'], strlen($ciphertext));
  456. } else {
  457. $ciphertext = '';
  458. $iv = $this->encryptIV;
  459. $start = 0;
  460. }
  461. for ($i = $start; $i < strlen($plaintext); $i+=8) {
  462. $block = substr($plaintext, $i, 8);
  463. $iv = $des[0]->_processBlock($iv, CRYPT_DES_ENCRYPT);
  464. $iv = $des[1]->_processBlock($iv, CRYPT_DES_DECRYPT);
  465. $xor= $des[2]->_processBlock($iv, CRYPT_DES_ENCRYPT);
  466. $iv = $block ^ $xor;
  467. if ($continuousBuffer && strlen($iv) != 8) {
  468. $buffer = array(
  469. 'encrypted' => $iv,
  470. 'xor' => substr($xor, strlen($iv))
  471. );
  472. }
  473. $ciphertext.= $iv;
  474. }
  475. if ($this->continuousBuffer) {
  476. $this->encryptIV = $iv;
  477. }
  478. break;
  479. case CRYPT_DES_MODE_OFB:
  480. $xor = $this->encryptIV;
  481. if (strlen($buffer['xor'])) {
  482. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  483. $block = substr($plaintext, $i, 8);
  484. if (strlen($block) > strlen($buffer['xor'])) {
  485. $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  486. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  487. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  488. $buffer['xor'].= $xor;
  489. }
  490. $key = $this->_string_shift($buffer['xor']);
  491. $ciphertext.= $block ^ $key;
  492. }
  493. } else {
  494. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  495. $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  496. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  497. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  498. $ciphertext.= substr($plaintext, $i, 8) ^ $xor;
  499. }
  500. $key = $xor;
  501. }
  502. if ($this->continuousBuffer) {
  503. $this->encryptIV = $xor;
  504. if ($start = strlen($plaintext) & 7) {
  505. $buffer['xor'] = substr($key, $start) . $buffer['xor'];
  506. }
  507. }
  508. }
  509. return $ciphertext;
  510. }
  511. /**
  512. * Decrypts a message.
  513. *
  514. * @access public
  515. * @param String $ciphertext
  516. */
  517. function decrypt($ciphertext)
  518. {
  519. if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
  520. $plaintext = $this->des[0]->decrypt($this->des[1]->encrypt($this->des[2]->decrypt($ciphertext)));
  521. return $this->_unpad($plaintext);
  522. }
  523. if ($this->paddable) {
  524. // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
  525. // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
  526. $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, chr(0));
  527. }
  528. if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
  529. if ($this->dechanged) {
  530. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  531. if ($this->mode == 'ncfb') {
  532. mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
  533. }
  534. $this->dechanged = false;
  535. }
  536. if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
  537. $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
  538. } else {
  539. $iv = &$this->decryptIV;
  540. $pos = &$this->debuffer['pos'];
  541. $len = strlen($ciphertext);
  542. $plaintext = '';
  543. $i = 0;
  544. if ($pos) {
  545. $orig_pos = $pos;
  546. $max = 8 - $pos;
  547. if ($len >= $max) {
  548. $i = $max;
  549. $len-= $max;
  550. $pos = 0;
  551. } else {
  552. $i = $len;
  553. $pos+= $len;
  554. $len = 0;
  555. }
  556. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  557. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  558. }
  559. if ($len >= 8) {
  560. $cb = substr($ciphertext, $i, $len - $len % 8);
  561. $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
  562. $iv = substr($cb, -8);
  563. $len%= 8;
  564. }
  565. if ($len) {
  566. $iv = mcrypt_generic($this->ecb, $iv);
  567. $cb = substr($ciphertext, -$len);
  568. $plaintext.= $iv ^ $cb;
  569. $iv = substr_replace($iv, $cb, 0, $len);
  570. $pos = $len;
  571. }
  572. return $plaintext;
  573. }
  574. if (!$this->continuousBuffer) {
  575. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  576. }
  577. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  578. }
  579. if (strlen($this->key) <= 8) {
  580. $this->des[0]->mode = $this->mode;
  581. $plaintext = $this->des[0]->decrypt($ciphertext);
  582. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  583. }
  584. if ($this->use_inline_crypt) {
  585. $inline = $this->inline_crypt;
  586. return $inline('decrypt', $this, $ciphertext);
  587. }
  588. $des = $this->des;
  589. $buffer = &$this->debuffer;
  590. $continuousBuffer = $this->continuousBuffer;
  591. $plaintext = '';
  592. switch ($this->mode) {
  593. case CRYPT_DES_MODE_ECB:
  594. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  595. $block = substr($ciphertext, $i, 8);
  596. $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
  597. $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
  598. $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
  599. $plaintext.= $block;
  600. }
  601. break;
  602. case CRYPT_DES_MODE_CBC:
  603. $xor = $this->decryptIV;
  604. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  605. $orig = $block = substr($ciphertext, $i, 8);
  606. $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
  607. $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
  608. $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
  609. $plaintext.= $block ^ $xor;
  610. $xor = $orig;
  611. }
  612. if ($this->continuousBuffer) {
  613. $this->decryptIV = $xor;
  614. }
  615. break;
  616. case CRYPT_DES_MODE_CTR:
  617. $xor = $this->decryptIV;
  618. if (strlen($buffer['ciphertext'])) {
  619. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  620. $block = substr($ciphertext, $i, 8);
  621. if (strlen($block) > strlen($buffer['ciphertext'])) {
  622. $key = $this->_generate_xor($xor);
  623. $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
  624. $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
  625. $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
  626. $buffer['ciphertext'].= $key;
  627. }
  628. $key = $this->_string_shift($buffer['ciphertext']);
  629. $plaintext.= $block ^ $key;
  630. }
  631. } else {
  632. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  633. $block = substr($ciphertext, $i, 8);
  634. $key = $this->_generate_xor($xor);
  635. $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
  636. $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
  637. $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
  638. $plaintext.= $block ^ $key;
  639. }
  640. }
  641. if ($this->continuousBuffer) {
  642. $this->decryptIV = $xor;
  643. if ($start = strlen($plaintext) & 7) {
  644. $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
  645. }
  646. }
  647. break;
  648. case CRYPT_DES_MODE_CFB:
  649. if (strlen($buffer['ciphertext'])) {
  650. $plaintext = $ciphertext ^ substr($this->decryptIV, strlen($buffer['ciphertext']));
  651. $buffer['ciphertext'].= substr($ciphertext, 0, strlen($plaintext));
  652. if (strlen($buffer['ciphertext']) != 8) {
  653. $block = $this->decryptIV;
  654. } else {
  655. $block = $buffer['ciphertext'];
  656. $xor = $des[0]->_processBlock($buffer['ciphertext'], CRYPT_DES_ENCRYPT);
  657. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  658. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  659. $buffer['ciphertext'] = '';
  660. }
  661. $start = strlen($plaintext);
  662. } else {
  663. $plaintext = '';
  664. $xor = $des[0]->_processBlock($this->decryptIV, CRYPT_DES_ENCRYPT);
  665. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  666. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  667. $start = 0;
  668. }
  669. for ($i = $start; $i < strlen($ciphertext); $i+=8) {
  670. $block = substr($ciphertext, $i, 8);
  671. $plaintext.= $block ^ $xor;
  672. if ($continuousBuffer && strlen($block) != 8) {
  673. $buffer['ciphertext'].= $block;
  674. $block = $xor;
  675. } else if (strlen($block) == 8) {
  676. $xor = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
  677. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  678. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  679. }
  680. }
  681. if ($this->continuousBuffer) {
  682. $this->decryptIV = $block;
  683. }
  684. break;
  685. case CRYPT_DES_MODE_OFB:
  686. $xor = $this->decryptIV;
  687. if (strlen($buffer['xor'])) {
  688. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  689. $block = substr($ciphertext, $i, 8);
  690. if (strlen($block) > strlen($buffer['xor'])) {
  691. $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  692. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  693. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  694. $buffer['xor'].= $xor;
  695. }
  696. $key = $this->_string_shift($buffer['xor']);
  697. $plaintext.= $block ^ $key;
  698. }
  699. } else {
  700. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  701. $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  702. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  703. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  704. $plaintext.= substr($ciphertext, $i, 8) ^ $xor;
  705. }
  706. $key = $xor;
  707. }
  708. if ($this->continuousBuffer) {
  709. $this->decryptIV = $xor;
  710. if ($start = strlen($ciphertext) & 7) {
  711. $buffer['xor'] = substr($key, $start) . $buffer['xor'];
  712. }
  713. }
  714. }
  715. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  716. }
  717. /**
  718. * Treat consecutive "packets" as if they are a continuous buffer.
  719. *
  720. * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
  721. * will yield different outputs:
  722. *
  723. * <code>
  724. * echo $des->encrypt(substr($plaintext, 0, 8));
  725. * echo $des->encrypt(substr($plaintext, 8, 8));
  726. * </code>
  727. * <code>
  728. * echo $des->encrypt($plaintext);
  729. * </code>
  730. *
  731. * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
  732. * another, as demonstrated with the following:
  733. *
  734. * <code>
  735. * $des->encrypt(substr($plaintext, 0, 8));
  736. * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
  737. * </code>
  738. * <code>
  739. * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
  740. * </code>
  741. *
  742. * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
  743. * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
  744. * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
  745. *
  746. * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
  747. * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
  748. * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
  749. * however, they are also less intuitive and more likely to cause you problems.
  750. *
  751. * @see Crypt_TripleDES::disableContinuousBuffer()
  752. * @access public
  753. */
  754. function enableContinuousBuffer()
  755. {
  756. $this->continuousBuffer = true;
  757. if ($this->mode == CRYPT_DES_MODE_3CBC) {
  758. $this->des[0]->enableContinuousBuffer();
  759. $this->des[1]->enableContinuousBuffer();
  760. $this->des[2]->enableContinuousBuffer();
  761. }
  762. }
  763. /**
  764. * Treat consecutive packets as if they are a discontinuous buffer.
  765. *
  766. * The default behavior.
  767. *
  768. * @see Crypt_TripleDES::enableContinuousBuffer()
  769. * @access public
  770. */
  771. function disableContinuousBuffer()
  772. {
  773. $this->continuousBuffer = false;
  774. $this->encryptIV = $this->iv;
  775. $this->decryptIV = $this->iv;
  776. $this->enchanged = true;
  777. $this->dechanged = true;
  778. $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
  779. $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
  780. if ($this->mode == CRYPT_DES_MODE_3CBC) {
  781. $this->des[0]->disableContinuousBuffer();
  782. $this->des[1]->disableContinuousBuffer();
  783. $this->des[2]->disableContinuousBuffer();
  784. }
  785. }
  786. }
  787. // vim: ts=4:sw=4:et:
  788. // vim6: fdl=1: