TripleDES.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. * 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. * @package Crypt_TripleDES
  75. * @author Jim Wigginton <terrafrost@php.net>
  76. * @access public
  77. */
  78. class Crypt_TripleDES extends Crypt_DES
  79. {
  80. /**
  81. * The default password key_size used by setPassword()
  82. *
  83. * @see Crypt_DES::password_key_size
  84. * @see Crypt_Base::password_key_size
  85. * @see Crypt_Base::setPassword()
  86. * @var Integer
  87. * @access private
  88. */
  89. var $password_key_size = 24;
  90. /**
  91. * The default salt used by setPassword()
  92. *
  93. * @see Crypt_Base::password_default_salt
  94. * @see Crypt_Base::setPassword()
  95. * @var String
  96. * @access private
  97. */
  98. var $password_default_salt = 'phpseclib';
  99. /**
  100. * The namespace used by the cipher for its constants.
  101. *
  102. * @see Crypt_DES::const_namespace
  103. * @see Crypt_Base::const_namespace
  104. * @var String
  105. * @access private
  106. */
  107. var $const_namespace = 'DES';
  108. /**
  109. * The mcrypt specific name of the cipher
  110. *
  111. * @see Crypt_DES::cipher_name_mcrypt
  112. * @see Crypt_Base::cipher_name_mcrypt
  113. * @var String
  114. * @access private
  115. */
  116. var $cipher_name_mcrypt = 'tripledes';
  117. /**
  118. * Optimizing value while CFB-encrypting
  119. *
  120. * @see Crypt_Base::cfb_init_len
  121. * @var Integer
  122. * @access private
  123. */
  124. var $cfb_init_len = 750;
  125. /**
  126. * max possible size of $key
  127. *
  128. * @see Crypt_TripleDES::setKey()
  129. * @see Crypt_DES::setKey()
  130. * @var String
  131. * @access private
  132. */
  133. var $key_size_max = 24;
  134. /**
  135. * Internal flag whether using CRYPT_DES_MODE_3CBC or not
  136. *
  137. * @var Boolean
  138. * @access private
  139. */
  140. var $mode_3cbc;
  141. /**
  142. * The Crypt_DES objects
  143. *
  144. * Used only if $mode_3cbc === true
  145. *
  146. * @var Array
  147. * @access private
  148. */
  149. var $des;
  150. /**
  151. * Default Constructor.
  152. *
  153. * Determines whether or not the mcrypt extension should be used.
  154. *
  155. * $mode could be:
  156. *
  157. * - CRYPT_DES_MODE_ECB
  158. *
  159. * - CRYPT_DES_MODE_CBC
  160. *
  161. * - CRYPT_DES_MODE_CTR
  162. *
  163. * - CRYPT_DES_MODE_CFB
  164. *
  165. * - CRYPT_DES_MODE_OFB
  166. *
  167. * - CRYPT_DES_MODE_3CBC
  168. *
  169. * If not explicitly set, CRYPT_DES_MODE_CBC will be used.
  170. *
  171. * @see Crypt_DES::Crypt_DES()
  172. * @see Crypt_Base::Crypt_Base()
  173. * @param optional Integer $mode
  174. * @access public
  175. */
  176. function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC)
  177. {
  178. switch ($mode) {
  179. // In case of CRYPT_DES_MODE_3CBC, we init as CRYPT_DES_MODE_CBC
  180. // and additional flag us internally as 3CBC
  181. case CRYPT_DES_MODE_3CBC:
  182. parent::Crypt_Base(CRYPT_DES_MODE_CBC);
  183. $this->mode_3cbc = true;
  184. // This three $des'es will do the 3CBC work (if $key > 64bits)
  185. $this->des = array(
  186. new Crypt_DES(CRYPT_DES_MODE_CBC),
  187. new Crypt_DES(CRYPT_DES_MODE_CBC),
  188. new Crypt_DES(CRYPT_DES_MODE_CBC),
  189. );
  190. // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
  191. $this->des[0]->disablePadding();
  192. $this->des[1]->disablePadding();
  193. $this->des[2]->disablePadding();
  194. break;
  195. // If not 3CBC, we init as usual
  196. default:
  197. parent::Crypt_Base($mode);
  198. }
  199. }
  200. /**
  201. * Sets the initialization vector. (optional)
  202. *
  203. * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explicitly set, it'll be assumed
  204. * to be all zero's.
  205. *
  206. * @see Crypt_Base::setIV()
  207. * @access public
  208. * @param String $iv
  209. */
  210. function setIV($iv)
  211. {
  212. parent::setIV($iv);
  213. if ($this->mode_3cbc) {
  214. $this->des[0]->setIV($iv);
  215. $this->des[1]->setIV($iv);
  216. $this->des[2]->setIV($iv);
  217. }
  218. }
  219. /**
  220. * Sets the key.
  221. *
  222. * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
  223. * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate.
  224. *
  225. * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
  226. *
  227. * If the key is not explicitly set, it'll be assumed to be all null bytes.
  228. *
  229. * @access public
  230. * @see Crypt_DES::setKey()
  231. * @see Crypt_Base::setKey()
  232. * @param String $key
  233. */
  234. function setKey($key)
  235. {
  236. $length = strlen($key);
  237. if ($length > 8) {
  238. $key = str_pad(substr($key, 0, 24), 24, chr(0));
  239. // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
  240. // http://php.net/function.mcrypt-encrypt#47973
  241. //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
  242. } else {
  243. $key = str_pad($key, 8, chr(0));
  244. }
  245. parent::setKey($key);
  246. // And in case of CRYPT_DES_MODE_3CBC:
  247. // if key <= 64bits we not need the 3 $des to work,
  248. // because we will then act as regular DES-CBC with just a <= 64bit key.
  249. // So only if the key > 64bits (> 8 bytes) we will call setKey() for the 3 $des.
  250. if ($this->mode_3cbc && $length > 8) {
  251. $this->des[0]->setKey(substr($key, 0, 8));
  252. $this->des[1]->setKey(substr($key, 8, 8));
  253. $this->des[2]->setKey(substr($key, 16, 8));
  254. }
  255. }
  256. /**
  257. * Encrypts a message.
  258. *
  259. * @see Crypt_Base::encrypt()
  260. * @access public
  261. * @param String $plaintext
  262. * @return String $cipertext
  263. */
  264. function encrypt($plaintext)
  265. {
  266. // parent::en/decrypt() is able to do all the work for all modes and keylengths,
  267. // except for: CRYPT_DES_MODE_3CBC (inner chaining CBC) with a key > 64bits
  268. // if the key is smaller then 8, do what we'd normally do
  269. if ($this->mode_3cbc && strlen($this->key) > 8) {
  270. return $this->des[2]->encrypt(
  271. $this->des[1]->decrypt(
  272. $this->des[0]->encrypt(
  273. $this->_pad($plaintext)
  274. )
  275. )
  276. );
  277. }
  278. return parent::encrypt($plaintext);
  279. }
  280. /**
  281. * Decrypts a message.
  282. *
  283. * @see Crypt_Base::decrypt()
  284. * @access public
  285. * @param String $ciphertext
  286. * @return String $plaintext
  287. */
  288. function decrypt($ciphertext)
  289. {
  290. if ($this->mode_3cbc && strlen($this->key) > 8) {
  291. return $this->_unpad(
  292. $this->des[0]->decrypt(
  293. $this->des[1]->encrypt(
  294. $this->des[2]->decrypt(
  295. str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, "\0")
  296. )
  297. )
  298. )
  299. );
  300. }
  301. return parent::decrypt($ciphertext);
  302. }
  303. /**
  304. * Treat consecutive "packets" as if they are a continuous buffer.
  305. *
  306. * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
  307. * will yield different outputs:
  308. *
  309. * <code>
  310. * echo $des->encrypt(substr($plaintext, 0, 8));
  311. * echo $des->encrypt(substr($plaintext, 8, 8));
  312. * </code>
  313. * <code>
  314. * echo $des->encrypt($plaintext);
  315. * </code>
  316. *
  317. * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
  318. * another, as demonstrated with the following:
  319. *
  320. * <code>
  321. * $des->encrypt(substr($plaintext, 0, 8));
  322. * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
  323. * </code>
  324. * <code>
  325. * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
  326. * </code>
  327. *
  328. * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
  329. * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
  330. * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
  331. *
  332. * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
  333. * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
  334. * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
  335. * however, they are also less intuitive and more likely to cause you problems.
  336. *
  337. * @see Crypt_Base::enableContinuousBuffer()
  338. * @see Crypt_TripleDES::disableContinuousBuffer()
  339. * @access public
  340. */
  341. function enableContinuousBuffer()
  342. {
  343. parent::enableContinuousBuffer();
  344. if ($this->mode_3cbc) {
  345. $this->des[0]->enableContinuousBuffer();
  346. $this->des[1]->enableContinuousBuffer();
  347. $this->des[2]->enableContinuousBuffer();
  348. }
  349. }
  350. /**
  351. * Treat consecutive packets as if they are a discontinuous buffer.
  352. *
  353. * The default behavior.
  354. *
  355. * @see Crypt_Base::disableContinuousBuffer()
  356. * @see Crypt_TripleDES::enableContinuousBuffer()
  357. * @access public
  358. */
  359. function disableContinuousBuffer()
  360. {
  361. parent::disableContinuousBuffer();
  362. if ($this->mode_3cbc) {
  363. $this->des[0]->disableContinuousBuffer();
  364. $this->des[1]->disableContinuousBuffer();
  365. $this->des[2]->disableContinuousBuffer();
  366. }
  367. }
  368. /**
  369. * Creates the key schedule
  370. *
  371. * @see Crypt_DES::_setupKey()
  372. * @see Crypt_Base::_setupKey()
  373. * @access private
  374. */
  375. function _setupKey()
  376. {
  377. switch (true) {
  378. // if $key <= 64bits we configure our internal pure-php cipher engine
  379. // to act as regular [1]DES, not as 3DES. mcrypt.so::tripledes does the same.
  380. case strlen($this->key) <= 8:
  381. $this->des_rounds = 1;
  382. break;
  383. // otherwise, if $key > 64bits, we configure our engine to work as 3DES.
  384. default:
  385. $this->des_rounds = 3;
  386. // (only) if 3CBC is used we have, of course, to setup the $des[0-2] keys also separately.
  387. if ($this->mode_3cbc) {
  388. $this->des[0]->_setupKey();
  389. $this->des[1]->_setupKey();
  390. $this->des[2]->_setupKey();
  391. // because $des[0-2] will, now, do all the work we can return here
  392. // not need unnecessary stress parent::_setupKey() with our, now unused, $key.
  393. return;
  394. }
  395. }
  396. // setup our key
  397. parent::_setupKey();
  398. }
  399. }