TripleDES.php 13 KB

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