TripleDES.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. <?php
  2. /**
  3. * Pure-PHP implementation of Triple DES.
  4. *
  5. * Uses mcrypt, if available, and an internal implementation, otherwise. Operates in the EDE3 mode (encrypt-decrypt-encrypt).
  6. *
  7. * PHP versions 4 and 5
  8. *
  9. * Here's a short example of how to use this library:
  10. * <code>
  11. * <?php
  12. * include 'Crypt/TripleDES.php';
  13. *
  14. * $des = new Crypt_TripleDES();
  15. *
  16. * $des->setKey('abcdefghijklmnopqrstuvwx');
  17. *
  18. * $size = 10 * 1024;
  19. * $plaintext = '';
  20. * for ($i = 0; $i < $size; $i++) {
  21. * $plaintext.= 'a';
  22. * }
  23. *
  24. * echo $des->decrypt($des->encrypt($plaintext));
  25. * ?>
  26. * </code>
  27. *
  28. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  29. * of this software and associated documentation files (the "Software"), to deal
  30. * in the Software without restriction, including without limitation the rights
  31. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  32. * copies of the Software, and to permit persons to whom the Software is
  33. * furnished to do so, subject to the following conditions:
  34. *
  35. * The above copyright notice and this permission notice shall be included in
  36. * all copies or substantial portions of the Software.
  37. *
  38. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  39. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  42. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  43. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  44. * THE SOFTWARE.
  45. *
  46. * @category Crypt
  47. * @package Crypt_TripleDES
  48. * @author Jim Wigginton <terrafrost@php.net>
  49. * @copyright 2007 Jim Wigginton
  50. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  51. * @link http://phpseclib.sourceforge.net
  52. */
  53. /**
  54. * Include Crypt_DES
  55. */
  56. if (!class_exists('Crypt_DES')) {
  57. include_once 'DES.php';
  58. }
  59. /**#@+
  60. * @access public
  61. * @see self::Crypt_TripleDES()
  62. */
  63. /**
  64. * Encrypt / decrypt using inner chaining
  65. *
  66. * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3).
  67. */
  68. define('CRYPT_MODE_3CBC', -2);
  69. /**
  70. * BC version of the above.
  71. */
  72. define('CRYPT_DES_MODE_3CBC', -2);
  73. /**
  74. * Encrypt / decrypt using outer chaining
  75. *
  76. * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC.
  77. */
  78. define('CRYPT_MODE_CBC3', CRYPT_MODE_CBC);
  79. /**
  80. * BC version of the above.
  81. */
  82. define('CRYPT_DES_MODE_CBC3', CRYPT_MODE_CBC3);
  83. /**#@-*/
  84. /**
  85. * Pure-PHP implementation of Triple DES.
  86. *
  87. * @package Crypt_TripleDES
  88. * @author Jim Wigginton <terrafrost@php.net>
  89. * @access public
  90. */
  91. class Crypt_TripleDES extends Crypt_DES
  92. {
  93. /**
  94. * Key Length (in bytes)
  95. *
  96. * @see Crypt_TripleDES::setKeyLength()
  97. * @var int
  98. * @access private
  99. */
  100. var $key_length = 24;
  101. /**
  102. * The default salt used by setPassword()
  103. *
  104. * @see Crypt_Base::password_default_salt
  105. * @see Crypt_Base::setPassword()
  106. * @var string
  107. * @access private
  108. */
  109. var $password_default_salt = 'phpseclib';
  110. /**
  111. * The namespace used by the cipher for its constants.
  112. *
  113. * @see Crypt_DES::const_namespace
  114. * @see Crypt_Base::const_namespace
  115. * @var string
  116. * @access private
  117. */
  118. var $const_namespace = 'DES';
  119. /**
  120. * The mcrypt specific name of the cipher
  121. *
  122. * @see Crypt_DES::cipher_name_mcrypt
  123. * @see Crypt_Base::cipher_name_mcrypt
  124. * @var string
  125. * @access private
  126. */
  127. var $cipher_name_mcrypt = 'tripledes';
  128. /**
  129. * Optimizing value while CFB-encrypting
  130. *
  131. * @see Crypt_Base::cfb_init_len
  132. * @var int
  133. * @access private
  134. */
  135. var $cfb_init_len = 750;
  136. /**
  137. * max possible size of $key
  138. *
  139. * @see self::setKey()
  140. * @see Crypt_DES::setKey()
  141. * @var string
  142. * @access private
  143. */
  144. var $key_length_max = 24;
  145. /**
  146. * Internal flag whether using CRYPT_DES_MODE_3CBC or not
  147. *
  148. * @var bool
  149. * @access private
  150. */
  151. var $mode_3cbc;
  152. /**
  153. * The Crypt_DES objects
  154. *
  155. * Used only if $mode_3cbc === true
  156. *
  157. * @var array
  158. * @access private
  159. */
  160. var $des;
  161. /**
  162. * Default Constructor.
  163. *
  164. * Determines whether or not the mcrypt extension should be used.
  165. *
  166. * $mode could be:
  167. *
  168. * - CRYPT_DES_MODE_ECB
  169. *
  170. * - CRYPT_DES_MODE_CBC
  171. *
  172. * - CRYPT_DES_MODE_CTR
  173. *
  174. * - CRYPT_DES_MODE_CFB
  175. *
  176. * - CRYPT_DES_MODE_OFB
  177. *
  178. * - CRYPT_DES_MODE_3CBC
  179. *
  180. * If not explicitly set, CRYPT_DES_MODE_CBC will be used.
  181. *
  182. * @see Crypt_DES::Crypt_DES()
  183. * @see Crypt_Base::Crypt_Base()
  184. * @param int $mode
  185. * @access public
  186. */
  187. function __construct($mode = CRYPT_MODE_CBC)
  188. {
  189. switch ($mode) {
  190. // In case of CRYPT_DES_MODE_3CBC, we init as CRYPT_DES_MODE_CBC
  191. // and additional flag us internally as 3CBC
  192. case CRYPT_DES_MODE_3CBC:
  193. parent::Crypt_Base(CRYPT_MODE_CBC);
  194. $this->mode_3cbc = true;
  195. // This three $des'es will do the 3CBC work (if $key > 64bits)
  196. $this->des = array(
  197. new Crypt_DES(CRYPT_MODE_CBC),
  198. new Crypt_DES(CRYPT_MODE_CBC),
  199. new Crypt_DES(CRYPT_MODE_CBC),
  200. );
  201. // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
  202. $this->des[0]->disablePadding();
  203. $this->des[1]->disablePadding();
  204. $this->des[2]->disablePadding();
  205. break;
  206. // If not 3CBC, we init as usual
  207. default:
  208. parent::__construct($mode);
  209. }
  210. }
  211. /**
  212. * PHP4 compatible Default Constructor.
  213. *
  214. * @see self::__construct()
  215. * @param int $mode
  216. * @access public
  217. */
  218. function Crypt_TripleDES($mode = CRYPT_MODE_CBC)
  219. {
  220. $this->__construct($mode);
  221. }
  222. /**
  223. * Test for engine validity
  224. *
  225. * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine()
  226. *
  227. * @see Crypt_Base::Crypt_Base()
  228. * @param int $engine
  229. * @access public
  230. * @return bool
  231. */
  232. function isValidEngine($engine)
  233. {
  234. if ($engine == CRYPT_ENGINE_OPENSSL) {
  235. $this->cipher_name_openssl_ecb = 'des-ede3';
  236. $mode = $this->_openssl_translate_mode();
  237. $this->cipher_name_openssl = $mode == 'ecb' ? 'des-ede3' : 'des-ede3-' . $mode;
  238. }
  239. return parent::isValidEngine($engine);
  240. }
  241. /**
  242. * Sets the initialization vector. (optional)
  243. *
  244. * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explicitly set, it'll be assumed
  245. * to be all zero's.
  246. *
  247. * @see Crypt_Base::setIV()
  248. * @access public
  249. * @param string $iv
  250. */
  251. function setIV($iv)
  252. {
  253. parent::setIV($iv);
  254. if ($this->mode_3cbc) {
  255. $this->des[0]->setIV($iv);
  256. $this->des[1]->setIV($iv);
  257. $this->des[2]->setIV($iv);
  258. }
  259. }
  260. /**
  261. * Sets the key length.
  262. *
  263. * Valid key lengths are 64, 128 and 192
  264. *
  265. * @see Crypt_Base:setKeyLength()
  266. * @access public
  267. * @param int $length
  268. */
  269. function setKeyLength($length)
  270. {
  271. $length >>= 3;
  272. switch (true) {
  273. case $length <= 8:
  274. $this->key_length = 8;
  275. break;
  276. case $length <= 16:
  277. $this->key_length = 16;
  278. break;
  279. default:
  280. $this->key_length = 24;
  281. }
  282. parent::setKeyLength($length);
  283. }
  284. /**
  285. * Sets the key.
  286. *
  287. * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
  288. * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate.
  289. *
  290. * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
  291. *
  292. * If the key is not explicitly set, it'll be assumed to be all null bytes.
  293. *
  294. * @access public
  295. * @see Crypt_DES::setKey()
  296. * @see Crypt_Base::setKey()
  297. * @param string $key
  298. */
  299. function setKey($key)
  300. {
  301. $length = $this->explicit_key_length ? $this->key_length : strlen($key);
  302. if ($length > 8) {
  303. $key = str_pad(substr($key, 0, 24), 24, chr(0));
  304. // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
  305. // http://php.net/function.mcrypt-encrypt#47973
  306. $key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
  307. } else {
  308. $key = str_pad($key, 8, chr(0));
  309. }
  310. parent::setKey($key);
  311. // And in case of CRYPT_DES_MODE_3CBC:
  312. // if key <= 64bits we not need the 3 $des to work,
  313. // because we will then act as regular DES-CBC with just a <= 64bit key.
  314. // So only if the key > 64bits (> 8 bytes) we will call setKey() for the 3 $des.
  315. if ($this->mode_3cbc && $length > 8) {
  316. $this->des[0]->setKey(substr($key, 0, 8));
  317. $this->des[1]->setKey(substr($key, 8, 8));
  318. $this->des[2]->setKey(substr($key, 16, 8));
  319. }
  320. }
  321. /**
  322. * Encrypts a message.
  323. *
  324. * @see Crypt_Base::encrypt()
  325. * @access public
  326. * @param string $plaintext
  327. * @return string $cipertext
  328. */
  329. function encrypt($plaintext)
  330. {
  331. // parent::en/decrypt() is able to do all the work for all modes and keylengths,
  332. // except for: CRYPT_MODE_3CBC (inner chaining CBC) with a key > 64bits
  333. // if the key is smaller then 8, do what we'd normally do
  334. if ($this->mode_3cbc && strlen($this->key) > 8) {
  335. return $this->des[2]->encrypt(
  336. $this->des[1]->decrypt(
  337. $this->des[0]->encrypt(
  338. $this->_pad($plaintext)
  339. )
  340. )
  341. );
  342. }
  343. return parent::encrypt($plaintext);
  344. }
  345. /**
  346. * Decrypts a message.
  347. *
  348. * @see Crypt_Base::decrypt()
  349. * @access public
  350. * @param string $ciphertext
  351. * @return string $plaintext
  352. */
  353. function decrypt($ciphertext)
  354. {
  355. if ($this->mode_3cbc && strlen($this->key) > 8) {
  356. return $this->_unpad(
  357. $this->des[0]->decrypt(
  358. $this->des[1]->encrypt(
  359. $this->des[2]->decrypt(
  360. str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, "\0")
  361. )
  362. )
  363. )
  364. );
  365. }
  366. return parent::decrypt($ciphertext);
  367. }
  368. /**
  369. * Treat consecutive "packets" as if they are a continuous buffer.
  370. *
  371. * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
  372. * will yield different outputs:
  373. *
  374. * <code>
  375. * echo $des->encrypt(substr($plaintext, 0, 8));
  376. * echo $des->encrypt(substr($plaintext, 8, 8));
  377. * </code>
  378. * <code>
  379. * echo $des->encrypt($plaintext);
  380. * </code>
  381. *
  382. * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
  383. * another, as demonstrated with the following:
  384. *
  385. * <code>
  386. * $des->encrypt(substr($plaintext, 0, 8));
  387. * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
  388. * </code>
  389. * <code>
  390. * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
  391. * </code>
  392. *
  393. * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
  394. * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
  395. * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
  396. *
  397. * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
  398. * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
  399. * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
  400. * however, they are also less intuitive and more likely to cause you problems.
  401. *
  402. * @see Crypt_Base::enableContinuousBuffer()
  403. * @see self::disableContinuousBuffer()
  404. * @access public
  405. */
  406. function enableContinuousBuffer()
  407. {
  408. parent::enableContinuousBuffer();
  409. if ($this->mode_3cbc) {
  410. $this->des[0]->enableContinuousBuffer();
  411. $this->des[1]->enableContinuousBuffer();
  412. $this->des[2]->enableContinuousBuffer();
  413. }
  414. }
  415. /**
  416. * Treat consecutive packets as if they are a discontinuous buffer.
  417. *
  418. * The default behavior.
  419. *
  420. * @see Crypt_Base::disableContinuousBuffer()
  421. * @see self::enableContinuousBuffer()
  422. * @access public
  423. */
  424. function disableContinuousBuffer()
  425. {
  426. parent::disableContinuousBuffer();
  427. if ($this->mode_3cbc) {
  428. $this->des[0]->disableContinuousBuffer();
  429. $this->des[1]->disableContinuousBuffer();
  430. $this->des[2]->disableContinuousBuffer();
  431. }
  432. }
  433. /**
  434. * Creates the key schedule
  435. *
  436. * @see Crypt_DES::_setupKey()
  437. * @see Crypt_Base::_setupKey()
  438. * @access private
  439. */
  440. function _setupKey()
  441. {
  442. switch (true) {
  443. // if $key <= 64bits we configure our internal pure-php cipher engine
  444. // to act as regular [1]DES, not as 3DES. mcrypt.so::tripledes does the same.
  445. case strlen($this->key) <= 8:
  446. $this->des_rounds = 1;
  447. break;
  448. // otherwise, if $key > 64bits, we configure our engine to work as 3DES.
  449. default:
  450. $this->des_rounds = 3;
  451. // (only) if 3CBC is used we have, of course, to setup the $des[0-2] keys also separately.
  452. if ($this->mode_3cbc) {
  453. $this->des[0]->_setupKey();
  454. $this->des[1]->_setupKey();
  455. $this->des[2]->_setupKey();
  456. // because $des[0-2] will, now, do all the work we can return here
  457. // not need unnecessary stress parent::_setupKey() with our, now unused, $key.
  458. return;
  459. }
  460. }
  461. // setup our key
  462. parent::_setupKey();
  463. }
  464. /**
  465. * Sets the internal crypt engine
  466. *
  467. * @see Crypt_Base::Crypt_Base()
  468. * @see Crypt_Base::setPreferredEngine()
  469. * @param int $engine
  470. * @access public
  471. * @return int
  472. */
  473. function setPreferredEngine($engine)
  474. {
  475. if ($this->mode_3cbc) {
  476. $this->des[0]->setPreferredEngine($engine);
  477. $this->des[1]->setPreferredEngine($engine);
  478. $this->des[2]->setPreferredEngine($engine);
  479. }
  480. return parent::setPreferredEngine($engine);
  481. }
  482. }