TripleDES.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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. * @version $Id: TripleDES.php,v 1.13 2010/02/26 03:40:25 terrafrost Exp $
  53. * @link http://phpseclib.sourceforge.net
  54. */
  55. /**
  56. * Include Crypt_DES
  57. */
  58. require_once('DES.php');
  59. /**
  60. * Encrypt / decrypt using inner chaining
  61. *
  62. * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3).
  63. */
  64. define('CRYPT_DES_MODE_3CBC', -2);
  65. /**
  66. * Encrypt / decrypt using outer chaining
  67. *
  68. * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC.
  69. */
  70. define('CRYPT_DES_MODE_CBC3', CRYPT_DES_MODE_CBC);
  71. /**
  72. * Pure-PHP implementation of Triple DES.
  73. *
  74. * @author Jim Wigginton <terrafrost@php.net>
  75. * @version 0.1.0
  76. * @access public
  77. * @package Crypt_TerraDES
  78. */
  79. class Crypt_TripleDES {
  80. /**
  81. * The Three Keys
  82. *
  83. * @see Crypt_TripleDES::setKey()
  84. * @var String
  85. * @access private
  86. */
  87. var $key = "\0\0\0\0\0\0\0\0";
  88. /**
  89. * The Encryption Mode
  90. *
  91. * @see Crypt_TripleDES::Crypt_TripleDES()
  92. * @var Integer
  93. * @access private
  94. */
  95. var $mode = CRYPT_DES_MODE_CBC;
  96. /**
  97. * Continuous Buffer status
  98. *
  99. * @see Crypt_TripleDES::enableContinuousBuffer()
  100. * @var Boolean
  101. * @access private
  102. */
  103. var $continuousBuffer = false;
  104. /**
  105. * Padding status
  106. *
  107. * @see Crypt_TripleDES::enablePadding()
  108. * @var Boolean
  109. * @access private
  110. */
  111. var $padding = true;
  112. /**
  113. * The Initialization Vector
  114. *
  115. * @see Crypt_TripleDES::setIV()
  116. * @var String
  117. * @access private
  118. */
  119. var $iv = "\0\0\0\0\0\0\0\0";
  120. /**
  121. * A "sliding" Initialization Vector
  122. *
  123. * @see Crypt_TripleDES::enableContinuousBuffer()
  124. * @var String
  125. * @access private
  126. */
  127. var $encryptIV = "\0\0\0\0\0\0\0\0";
  128. /**
  129. * A "sliding" Initialization Vector
  130. *
  131. * @see Crypt_TripleDES::enableContinuousBuffer()
  132. * @var String
  133. * @access private
  134. */
  135. var $decryptIV = "\0\0\0\0\0\0\0\0";
  136. /**
  137. * The Crypt_DES objects
  138. *
  139. * @var Array
  140. * @access private
  141. */
  142. var $des;
  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 Crypt_TripleDES::encrypt()
  150. * @var String
  151. * @access private
  152. */
  153. var $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 Crypt_TripleDES::decrypt()
  161. * @var String
  162. * @access private
  163. */
  164. var $demcrypt;
  165. /**
  166. * Does the enmcrypt resource need to be (re)initialized?
  167. *
  168. * @see Crypt_TripleDES::setKey()
  169. * @see Crypt_TripleDES::setIV()
  170. * @var Boolean
  171. * @access private
  172. */
  173. var $enchanged = true;
  174. /**
  175. * Does the demcrypt resource need to be (re)initialized?
  176. *
  177. * @see Crypt_TripleDES::setKey()
  178. * @see Crypt_TripleDES::setIV()
  179. * @var Boolean
  180. * @access private
  181. */
  182. var $dechanged = true;
  183. /**
  184. * Is the mode one that is paddable?
  185. *
  186. * @see Crypt_TripleDES::Crypt_TripleDES()
  187. * @var Boolean
  188. * @access private
  189. */
  190. var $paddable = false;
  191. /**
  192. * Encryption buffer for CTR, OFB and CFB modes
  193. *
  194. * @see Crypt_TripleDES::encrypt()
  195. * @var String
  196. * @access private
  197. */
  198. var $enbuffer = '';
  199. /**
  200. * Decryption buffer for CTR, OFB and CFB modes
  201. *
  202. * @see Crypt_TripleDES::decrypt()
  203. * @var String
  204. * @access private
  205. */
  206. var $debuffer = '';
  207. /**
  208. * mcrypt resource for CFB mode
  209. *
  210. * @see Crypt_TripleDES::encrypt()
  211. * @see Crypt_TripleDES::decrypt()
  212. * @var String
  213. * @access private
  214. */
  215. var $ecb;
  216. /**
  217. * Default Constructor.
  218. *
  219. * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be
  220. * CRYPT_DES_MODE_ECB or CRYPT_DES_MODE_CBC. If not explictly set, CRYPT_DES_MODE_CBC will be used.
  221. *
  222. * @param optional Integer $mode
  223. * @return Crypt_TripleDES
  224. * @access public
  225. */
  226. function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC)
  227. {
  228. if ( !defined('CRYPT_DES_MODE') ) {
  229. switch (true) {
  230. case extension_loaded('mcrypt'):
  231. // i'd check to see if des was supported, by doing in_array('des', mcrypt_list_algorithms('')),
  232. // but since that can be changed after the object has been created, there doesn't seem to be
  233. // a lot of point...
  234. define('CRYPT_DES_MODE', CRYPT_DES_MODE_MCRYPT);
  235. break;
  236. default:
  237. define('CRYPT_DES_MODE', CRYPT_DES_MODE_INTERNAL);
  238. }
  239. }
  240. if ( $mode == CRYPT_DES_MODE_3CBC ) {
  241. $this->mode = CRYPT_DES_MODE_3CBC;
  242. $this->des = array(
  243. new Crypt_DES(CRYPT_DES_MODE_CBC),
  244. new Crypt_DES(CRYPT_DES_MODE_CBC),
  245. new Crypt_DES(CRYPT_DES_MODE_CBC)
  246. );
  247. // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
  248. $this->des[0]->disablePadding();
  249. $this->des[1]->disablePadding();
  250. $this->des[2]->disablePadding();
  251. return;
  252. }
  253. switch ( CRYPT_DES_MODE ) {
  254. case CRYPT_DES_MODE_MCRYPT:
  255. switch ($mode) {
  256. case CRYPT_DES_MODE_ECB:
  257. $this->paddable = true;
  258. $this->mode = MCRYPT_MODE_ECB;
  259. break;
  260. case CRYPT_DES_MODE_CTR:
  261. $this->mode = 'ctr';
  262. break;
  263. case CRYPT_DES_MODE_CFB:
  264. $this->mode = 'ncfb';
  265. break;
  266. case CRYPT_DES_MODE_OFB:
  267. $this->mode = MCRYPT_MODE_NOFB;
  268. break;
  269. case CRYPT_DES_MODE_CBC:
  270. default:
  271. $this->paddable = true;
  272. $this->mode = MCRYPT_MODE_CBC;
  273. }
  274. break;
  275. default:
  276. $this->des = array(
  277. new Crypt_DES(CRYPT_DES_MODE_ECB),
  278. new Crypt_DES(CRYPT_DES_MODE_ECB),
  279. new Crypt_DES(CRYPT_DES_MODE_ECB)
  280. );
  281. // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
  282. $this->des[0]->disablePadding();
  283. $this->des[1]->disablePadding();
  284. $this->des[2]->disablePadding();
  285. switch ($mode) {
  286. case CRYPT_DES_MODE_ECB:
  287. case CRYPT_DES_MODE_CBC:
  288. $this->paddable = true;
  289. $this->mode = $mode;
  290. break;
  291. case CRYPT_DES_MODE_CTR:
  292. case CRYPT_DES_MODE_CFB:
  293. case CRYPT_DES_MODE_OFB:
  294. $this->mode = $mode;
  295. break;
  296. default:
  297. $this->paddable = true;
  298. $this->mode = CRYPT_DES_MODE_CBC;
  299. }
  300. }
  301. }
  302. /**
  303. * Sets the key.
  304. *
  305. * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
  306. * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate.
  307. *
  308. * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
  309. *
  310. * If the key is not explicitly set, it'll be assumed to be all zero's.
  311. *
  312. * @access public
  313. * @param String $key
  314. */
  315. function setKey($key)
  316. {
  317. $length = strlen($key);
  318. if ($length > 8) {
  319. $key = str_pad($key, 24, chr(0));
  320. // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
  321. // http://php.net/function.mcrypt-encrypt#47973
  322. //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
  323. } else {
  324. $key = str_pad($key, 8, chr(0));
  325. }
  326. $this->key = $key;
  327. switch (true) {
  328. case CRYPT_DES_MODE == CRYPT_DES_MODE_INTERNAL:
  329. case $this->mode == CRYPT_DES_MODE_3CBC:
  330. $this->des[0]->setKey(substr($key, 0, 8));
  331. $this->des[1]->setKey(substr($key, 8, 8));
  332. $this->des[2]->setKey(substr($key, 16, 8));
  333. }
  334. $this->enchanged = $this->dechanged = true;
  335. }
  336. /**
  337. * Sets the initialization vector. (optional)
  338. *
  339. * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explictly set, it'll be assumed
  340. * to be all zero's.
  341. *
  342. * @access public
  343. * @param String $iv
  344. */
  345. function setIV($iv)
  346. {
  347. $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, 8), 8, chr(0));
  348. if ($this->mode == CRYPT_DES_MODE_3CBC) {
  349. $this->des[0]->setIV($iv);
  350. $this->des[1]->setIV($iv);
  351. $this->des[2]->setIV($iv);
  352. }
  353. $this->enchanged = $this->dechanged = true;
  354. }
  355. /**
  356. * Generate CTR XOR encryption key
  357. *
  358. * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
  359. * plaintext / ciphertext in CTR mode.
  360. *
  361. * @see Crypt_TripleDES::decrypt()
  362. * @see Crypt_TripleDES::encrypt()
  363. * @access private
  364. * @param Integer $length
  365. * @param String $iv
  366. */
  367. function _generate_xor($length, &$iv)
  368. {
  369. $xor = '';
  370. $num_blocks = ($length + 7) >> 3;
  371. for ($i = 0; $i < $num_blocks; $i++) {
  372. $xor.= $iv;
  373. for ($j = 4; $j <= 8; $j+=4) {
  374. $temp = substr($iv, -$j, 4);
  375. switch ($temp) {
  376. case "\xFF\xFF\xFF\xFF":
  377. $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
  378. break;
  379. case "\x7F\xFF\xFF\xFF":
  380. $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
  381. break 2;
  382. default:
  383. extract(unpack('Ncount', $temp));
  384. $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
  385. break 2;
  386. }
  387. }
  388. }
  389. return $xor;
  390. }
  391. /**
  392. * Encrypts a message.
  393. *
  394. * @access public
  395. * @param String $plaintext
  396. */
  397. function encrypt($plaintext)
  398. {
  399. if ($this->paddable) {
  400. $plaintext = $this->_pad($plaintext);
  401. }
  402. // if the key is smaller then 8, do what we'd normally do
  403. if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
  404. $ciphertext = $this->des[2]->encrypt($this->des[1]->decrypt($this->des[0]->encrypt($plaintext)));
  405. return $ciphertext;
  406. }
  407. if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
  408. if ($this->enchanged) {
  409. if (!isset($this->enmcrypt)) {
  410. $this->enmcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
  411. }
  412. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  413. if ($this->mode != 'ncfb') {
  414. $this->enchanged = false;
  415. }
  416. }
  417. if ($this->mode != 'ncfb') {
  418. $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
  419. } else {
  420. if ($this->enchanged) {
  421. $this->ecb = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
  422. mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
  423. $this->enchanged = false;
  424. }
  425. if (strlen($this->enbuffer)) {
  426. $ciphertext = $plaintext ^ substr($this->encryptIV, strlen($this->enbuffer));
  427. $this->enbuffer.= $ciphertext;
  428. if (strlen($this->enbuffer) == 8) {
  429. $this->encryptIV = $this->enbuffer;
  430. $this->enbuffer = '';
  431. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  432. }
  433. $plaintext = substr($plaintext, strlen($ciphertext));
  434. } else {
  435. $ciphertext = '';
  436. }
  437. $last_pos = strlen($plaintext) & 0xFFFFFFF8;
  438. $ciphertext.= $last_pos ? mcrypt_generic($this->enmcrypt, substr($plaintext, 0, $last_pos)) : '';
  439. if (strlen($plaintext) & 0x7) {
  440. if (strlen($ciphertext)) {
  441. $this->encryptIV = substr($ciphertext, -8);
  442. }
  443. $this->encryptIV = mcrypt_generic($this->ecb, $this->encryptIV);
  444. $this->enbuffer = substr($plaintext, $last_pos) ^ $this->encryptIV;
  445. $ciphertext.= $this->enbuffer;
  446. }
  447. }
  448. if (!$this->continuousBuffer) {
  449. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  450. }
  451. return $ciphertext;
  452. }
  453. if (strlen($this->key) <= 8) {
  454. $this->des[0]->mode = $this->mode;
  455. return $this->des[0]->encrypt($plaintext);
  456. }
  457. $des = $this->des;
  458. $buffer = &$this->enbuffer;
  459. $continuousBuffer = $this->continuousBuffer;
  460. $ciphertext = '';
  461. switch ($this->mode) {
  462. case CRYPT_DES_MODE_ECB:
  463. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  464. $block = substr($plaintext, $i, 8);
  465. // all of these _processBlock calls could, in theory, be put in a function - say Crypt_TripleDES::_ede_encrypt() or something.
  466. // only problem with that: it would slow encryption and decryption down. $this->des would have to be called every time that
  467. // function is called, instead of once for the whole string of text that's being encrypted, which would, in turn, make
  468. // encryption and decryption take more time, per this:
  469. //
  470. // http://blog.libssh2.org/index.php?/archives/21-Compiled-Variables.html
  471. $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
  472. $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
  473. $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
  474. $ciphertext.= $block;
  475. }
  476. break;
  477. case CRYPT_DES_MODE_CBC:
  478. $xor = $this->encryptIV;
  479. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  480. $block = substr($plaintext, $i, 8) ^ $xor;
  481. $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
  482. $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
  483. $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
  484. $xor = $block;
  485. $ciphertext.= $block;
  486. }
  487. if ($this->continuousBuffer) {
  488. $this->encryptIV = $xor;
  489. }
  490. break;
  491. case CRYPT_DES_MODE_CTR:
  492. $xor = $this->encryptIV;
  493. if (strlen($buffer)) {
  494. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  495. $block = substr($plaintext, $i, 8);
  496. $key = $this->_generate_xor(8, $xor);
  497. $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
  498. $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
  499. $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
  500. $buffer.= $key;
  501. $key = $this->_string_shift($buffer, 8);
  502. $ciphertext.= $block ^ $key;
  503. }
  504. } else {
  505. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  506. $block = substr($plaintext, $i, 8);
  507. $key = $this->_generate_xor(8, $xor);
  508. $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
  509. $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
  510. $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
  511. $ciphertext.= $block ^ $key;
  512. }
  513. }
  514. if ($this->continuousBuffer) {
  515. $this->encryptIV = $xor;
  516. if ($start = strlen($plaintext) & 7) {
  517. $buffer = substr($key, $start) . $buffer;
  518. }
  519. }
  520. break;
  521. case CRYPT_DES_MODE_CFB:
  522. if (!empty($buffer['xor'])) {
  523. $ciphertext = $plaintext ^ $buffer['xor'];
  524. $iv = $buffer['encrypted'] . $ciphertext;
  525. $start = strlen($ciphertext);
  526. $buffer['encrypted'].= $ciphertext;
  527. $buffer['xor'] = substr($buffer['xor'], strlen($ciphertext));
  528. } else {
  529. $ciphertext = '';
  530. $iv = $this->encryptIV;
  531. $start = 0;
  532. }
  533. for ($i = $start; $i < strlen($plaintext); $i+=8) {
  534. $block = substr($plaintext, $i, 8);
  535. $iv = $des[0]->_processBlock($iv, CRYPT_DES_ENCRYPT);
  536. $iv = $des[1]->_processBlock($iv, CRYPT_DES_DECRYPT);
  537. $xor= $des[2]->_processBlock($iv, CRYPT_DES_ENCRYPT);
  538. $iv = $block ^ $xor;
  539. if ($continuousBuffer && strlen($iv) != 8) {
  540. $buffer = array(
  541. 'encrypted' => $iv,
  542. 'xor' => substr($xor, strlen($iv))
  543. );
  544. }
  545. $ciphertext.= $iv;
  546. }
  547. if ($this->continuousBuffer) {
  548. $this->encryptIV = $iv;
  549. }
  550. break;
  551. case CRYPT_DES_MODE_OFB:
  552. $xor = $this->encryptIV;
  553. if (strlen($buffer)) {
  554. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  555. $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  556. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  557. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  558. $buffer.= $xor;
  559. $key = $this->_string_shift($buffer, 8);
  560. $ciphertext.= substr($plaintext, $i, 8) ^ $key;
  561. }
  562. } else {
  563. for ($i = 0; $i < strlen($plaintext); $i+=8) {
  564. $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  565. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  566. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  567. $ciphertext.= substr($plaintext, $i, 8) ^ $xor;
  568. }
  569. $key = $xor;
  570. }
  571. if ($this->continuousBuffer) {
  572. $this->encryptIV = $xor;
  573. if ($start = strlen($plaintext) & 7) {
  574. $buffer = substr($key, $start) . $buffer;
  575. }
  576. }
  577. }
  578. return $ciphertext;
  579. }
  580. /**
  581. * Decrypts a message.
  582. *
  583. * @access public
  584. * @param String $ciphertext
  585. */
  586. function decrypt($ciphertext)
  587. {
  588. if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
  589. $plaintext = $this->des[0]->decrypt($this->des[1]->encrypt($this->des[2]->decrypt($ciphertext)));
  590. return $this->_unpad($plaintext);
  591. }
  592. if ($this->paddable) {
  593. // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
  594. // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
  595. $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, chr(0));
  596. }
  597. if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
  598. if ($this->dechanged) {
  599. if (!isset($this->demcrypt)) {
  600. $this->demcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
  601. }
  602. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  603. if ($this->mode != 'ncfb') {
  604. $this->dechanged = false;
  605. }
  606. }
  607. if ($this->mode != 'ncfb') {
  608. $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
  609. } else {
  610. if ($this->dechanged) {
  611. $this->ecb = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
  612. mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
  613. $this->dechanged = false;
  614. }
  615. if (strlen($this->debuffer)) {
  616. $plaintext = $ciphertext ^ substr($this->decryptIV, strlen($this->debuffer));
  617. $this->debuffer.= substr($ciphertext, 0, strlen($plaintext));
  618. if (strlen($this->debuffer) == 8) {
  619. $this->decryptIV = $this->debuffer;
  620. $this->debuffer = '';
  621. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  622. }
  623. $ciphertext = substr($ciphertext, strlen($plaintext));
  624. } else {
  625. $plaintext = '';
  626. }
  627. $last_pos = strlen($ciphertext) & 0xFFFFFFF8;
  628. $plaintext.= $last_pos ? mdecrypt_generic($this->demcrypt, substr($ciphertext, 0, $last_pos)) : '';
  629. if (strlen($ciphertext) & 0x7) {
  630. if (strlen($plaintext)) {
  631. $this->decryptIV = substr($ciphertext, $last_pos - 8, 8);
  632. }
  633. $this->decryptIV = mcrypt_generic($this->ecb, $this->decryptIV);
  634. $this->debuffer = substr($ciphertext, $last_pos);
  635. $plaintext.= $this->debuffer ^ $this->decryptIV;
  636. }
  637. return $plaintext;
  638. }
  639. if (!$this->continuousBuffer) {
  640. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  641. }
  642. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  643. }
  644. if (strlen($this->key) <= 8) {
  645. $this->des[0]->mode = $this->mode;
  646. $plaintext = $this->des[0]->decrypt($ciphertext);
  647. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  648. }
  649. $des = $this->des;
  650. $buffer = &$this->enbuffer;
  651. $continuousBuffer = $this->continuousBuffer;
  652. $plaintext = '';
  653. switch ($this->mode) {
  654. case CRYPT_DES_MODE_ECB:
  655. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  656. $block = substr($ciphertext, $i, 8);
  657. $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
  658. $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
  659. $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
  660. $plaintext.= $block;
  661. }
  662. break;
  663. case CRYPT_DES_MODE_CBC:
  664. $xor = $this->decryptIV;
  665. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  666. $orig = $block = substr($ciphertext, $i, 8);
  667. $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
  668. $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
  669. $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
  670. $plaintext.= $block ^ $xor;
  671. $xor = $orig;
  672. }
  673. if ($this->continuousBuffer) {
  674. $this->decryptIV = $xor;
  675. }
  676. break;
  677. case CRYPT_DES_MODE_CTR:
  678. $xor = $this->decryptIV;
  679. if (strlen($buffer)) {
  680. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  681. $block = substr($ciphertext, $i, 8);
  682. $key = $this->_generate_xor(8, $xor);
  683. $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
  684. $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
  685. $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
  686. $buffer.= $key;
  687. $key = $this->_string_shift($buffer, 8);
  688. $plaintext.= $block ^ $key;
  689. }
  690. } else {
  691. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  692. $block = substr($ciphertext, $i, 8);
  693. $key = $this->_generate_xor(8, $xor);
  694. $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
  695. $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
  696. $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
  697. $plaintext.= $block ^ $key;
  698. }
  699. }
  700. if ($this->continuousBuffer) {
  701. $this->decryptIV = $xor;
  702. if ($start = strlen($plaintext) & 7) {
  703. $buffer = substr($key, $start) . $buffer;
  704. }
  705. }
  706. break;
  707. case CRYPT_DES_MODE_CFB:
  708. if (!empty($buffer['ciphertext'])) {
  709. $plaintext = $ciphertext ^ substr($this->decryptIV, strlen($buffer['ciphertext']));
  710. $buffer['ciphertext'].= substr($ciphertext, 0, strlen($plaintext));
  711. if (strlen($buffer['ciphertext']) == 8) {
  712. $xor = $des[0]->_processBlock($buffer['ciphertext'], CRYPT_DES_ENCRYPT);
  713. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  714. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  715. $buffer['ciphertext'] = '';
  716. }
  717. $start = strlen($plaintext);
  718. $block = $this->decryptIV;
  719. } else {
  720. $plaintext = '';
  721. $xor = $des[0]->_processBlock($this->decryptIV, CRYPT_DES_ENCRYPT);
  722. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  723. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  724. $start = 0;
  725. }
  726. for ($i = $start; $i < strlen($ciphertext); $i+=8) {
  727. $block = substr($ciphertext, $i, 8);
  728. $plaintext.= $block ^ $xor;
  729. if ($continuousBuffer && strlen($block) != 8) {
  730. $buffer['ciphertext'].= $block;
  731. $block = $xor;
  732. } else if (strlen($block) == 8) {
  733. $xor = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
  734. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  735. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  736. }
  737. }
  738. if ($this->continuousBuffer) {
  739. $this->decryptIV = $block;
  740. }
  741. break;
  742. case CRYPT_DES_MODE_OFB:
  743. $xor = $this->decryptIV;
  744. if (strlen($buffer)) {
  745. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  746. $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  747. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  748. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  749. $buffer.= $xor;
  750. $key = $this->_string_shift($buffer, 8);
  751. $plaintext.= substr($ciphertext, $i, 8) ^ $key;
  752. }
  753. } else {
  754. for ($i = 0; $i < strlen($ciphertext); $i+=8) {
  755. $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  756. $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
  757. $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
  758. $plaintext.= substr($ciphertext, $i, 8) ^ $xor;
  759. }
  760. $key = $xor;
  761. }
  762. if ($this->continuousBuffer) {
  763. $this->decryptIV = $xor;
  764. if ($start = strlen($ciphertext) & 7) {
  765. $buffer = substr($key, $start) . $buffer;
  766. }
  767. }
  768. }
  769. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  770. }
  771. /**
  772. * Treat consecutive "packets" as if they are a continuous buffer.
  773. *
  774. * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
  775. * will yield different outputs:
  776. *
  777. * <code>
  778. * echo $des->encrypt(substr($plaintext, 0, 8));
  779. * echo $des->encrypt(substr($plaintext, 8, 8));
  780. * </code>
  781. * <code>
  782. * echo $des->encrypt($plaintext);
  783. * </code>
  784. *
  785. * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
  786. * another, as demonstrated with the following:
  787. *
  788. * <code>
  789. * $des->encrypt(substr($plaintext, 0, 8));
  790. * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
  791. * </code>
  792. * <code>
  793. * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
  794. * </code>
  795. *
  796. * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
  797. * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
  798. * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
  799. *
  800. * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
  801. * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
  802. * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
  803. * however, they are also less intuitive and more likely to cause you problems.
  804. *
  805. * @see Crypt_TripleDES::disableContinuousBuffer()
  806. * @access public
  807. */
  808. function enableContinuousBuffer()
  809. {
  810. $this->continuousBuffer = true;
  811. if ($this->mode == CRYPT_DES_MODE_3CBC) {
  812. $this->des[0]->enableContinuousBuffer();
  813. $this->des[1]->enableContinuousBuffer();
  814. $this->des[2]->enableContinuousBuffer();
  815. }
  816. }
  817. /**
  818. * Treat consecutive packets as if they are a discontinuous buffer.
  819. *
  820. * The default behavior.
  821. *
  822. * @see Crypt_TripleDES::enableContinuousBuffer()
  823. * @access public
  824. */
  825. function disableContinuousBuffer()
  826. {
  827. $this->continuousBuffer = false;
  828. $this->encryptIV = $this->iv;
  829. $this->decryptIV = $this->iv;
  830. if ($this->mode == CRYPT_DES_MODE_3CBC) {
  831. $this->des[0]->disableContinuousBuffer();
  832. $this->des[1]->disableContinuousBuffer();
  833. $this->des[2]->disableContinuousBuffer();
  834. }
  835. }
  836. /**
  837. * Pad "packets".
  838. *
  839. * DES works by encrypting eight bytes at a time. If you ever need to encrypt or decrypt something that's not
  840. * a multiple of eight, it becomes necessary to pad the input so that it's length is a multiple of eight.
  841. *
  842. * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH1,
  843. * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
  844. * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
  845. * transmitted separately)
  846. *
  847. * @see Crypt_TripleDES::disablePadding()
  848. * @access public
  849. */
  850. function enablePadding()
  851. {
  852. $this->padding = true;
  853. }
  854. /**
  855. * Do not pad packets.
  856. *
  857. * @see Crypt_TripleDES::enablePadding()
  858. * @access public
  859. */
  860. function disablePadding()
  861. {
  862. $this->padding = false;
  863. }
  864. /**
  865. * Pads a string
  866. *
  867. * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize (8).
  868. * 8 - (strlen($text) & 7) bytes are added, each of which is equal to chr(8 - (strlen($text) & 7)
  869. *
  870. * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
  871. * and padding will, hence forth, be enabled.
  872. *
  873. * @see Crypt_TripleDES::_unpad()
  874. * @access private
  875. */
  876. function _pad($text)
  877. {
  878. $length = strlen($text);
  879. if (!$this->padding) {
  880. if (($length & 7) == 0) {
  881. return $text;
  882. } else {
  883. user_error("The plaintext's length ($length) is not a multiple of the block size (8)", E_USER_NOTICE);
  884. $this->padding = true;
  885. }
  886. }
  887. $pad = 8 - ($length & 7);
  888. return str_pad($text, $length + $pad, chr($pad));
  889. }
  890. /**
  891. * Unpads a string
  892. *
  893. * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
  894. * and false will be returned.
  895. *
  896. * @see Crypt_TripleDES::_pad()
  897. * @access private
  898. */
  899. function _unpad($text)
  900. {
  901. if (!$this->padding) {
  902. return $text;
  903. }
  904. $length = ord($text[strlen($text) - 1]);
  905. if (!$length || $length > 8) {
  906. return false;
  907. }
  908. return substr($text, 0, -$length);
  909. }
  910. /**
  911. * String Shift
  912. *
  913. * Inspired by array_shift
  914. *
  915. * @param String $string
  916. * @param optional Integer $index
  917. * @return String
  918. * @access private
  919. */
  920. function _string_shift(&$string, $index = 1)
  921. {
  922. $substr = substr($string, 0, $index);
  923. $string = substr($string, $index);
  924. return $substr;
  925. }
  926. }
  927. // vim: ts=4:sw=4:et:
  928. // vim6: fdl=1: