Crypt_AES.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Pure-PHP implementation of AES.
  5. *
  6. * Uses mcrypt, if available, and an internal implementation, otherwise.
  7. *
  8. * PHP versions 4 and 5
  9. *
  10. * If {@link Crypt_AES::setKeyLength() setKeyLength()} isn't called, it'll be calculated from
  11. * {@link Crypt_AES::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's 136-bits
  12. * it'll be null-padded to 160-bits and 160 bits will be the key length until {@link Crypt_Rijndael::setKey() setKey()}
  13. * is called, again, at which point, it'll be recalculated.
  14. *
  15. * Since Crypt_AES extends Crypt_Rijndael, some functions are available to be called that, in the context of AES, don't
  16. * make a whole lot of sense. {@link Crypt_AES::setBlockLength() setBlockLength()}, for instance. Calling that function,
  17. * however possible, won't do anything (AES has a fixed block length whereas Rijndael has a variable one).
  18. *
  19. * Here's a short example of how to use this library:
  20. * <code>
  21. * <?php
  22. * include('Crypt/AES.php');
  23. *
  24. * $aes = new Crypt_AES();
  25. *
  26. * $aes->setKey('abcdefghijklmnop');
  27. *
  28. * $size = 10 * 1024;
  29. * $plaintext = '';
  30. * for ($i = 0; $i < $size; $i++) {
  31. * $plaintext.= 'a';
  32. * }
  33. *
  34. * echo $aes->decrypt($aes->encrypt($plaintext));
  35. * ?>
  36. * </code>
  37. *
  38. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  39. * of this software and associated documentation files (the "Software"), to deal
  40. * in the Software without restriction, including without limitation the rights
  41. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  42. * copies of the Software, and to permit persons to whom the Software is
  43. * furnished to do so, subject to the following conditions:
  44. *
  45. * The above copyright notice and this permission notice shall be included in
  46. * all copies or substantial portions of the Software.
  47. *
  48. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  49. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  50. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  51. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  52. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  53. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  54. * THE SOFTWARE.
  55. *
  56. * @category Crypt
  57. * @package Crypt_AES
  58. * @author Jim Wigginton <terrafrost@php.net>
  59. * @copyright MMVIII Jim Wigginton
  60. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  61. * @link http://phpseclib.sourceforge.net
  62. */
  63. /**#@+
  64. * @access public
  65. * @see Crypt_AES::encrypt()
  66. * @see Crypt_AES::decrypt()
  67. */
  68. /**
  69. * Encrypt / decrypt using the Counter mode.
  70. *
  71. * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
  72. *
  73. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
  74. */
  75. define('CRYPT_AES_MODE_CTR', -1);
  76. /**
  77. * Encrypt / decrypt using the Electronic Code Book mode.
  78. *
  79. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
  80. */
  81. define('CRYPT_AES_MODE_ECB', 1);
  82. /**
  83. * Encrypt / decrypt using the Code Book Chaining mode.
  84. *
  85. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
  86. */
  87. define('CRYPT_AES_MODE_CBC', 2);
  88. /**
  89. * Encrypt / decrypt using the Cipher Feedback mode.
  90. *
  91. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
  92. */
  93. define('CRYPT_AES_MODE_CFB', 3);
  94. /**
  95. * Encrypt / decrypt using the Cipher Feedback mode.
  96. *
  97. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
  98. */
  99. define('CRYPT_AES_MODE_OFB', 4);
  100. /**#@-*/
  101. /**#@+
  102. * @access private
  103. * @see Crypt_AES::Crypt_AES()
  104. */
  105. /**
  106. * Toggles the internal implementation
  107. */
  108. define('CRYPT_AES_MODE_INTERNAL', 1);
  109. /**
  110. * Toggles the mcrypt implementation
  111. */
  112. define('CRYPT_AES_MODE_MCRYPT', 2);
  113. /**#@-*/
  114. /**
  115. * Pure-PHP implementation of AES.
  116. *
  117. * @author Jim Wigginton <terrafrost@php.net>
  118. * @version 0.1.0
  119. * @access public
  120. * @package Crypt_AES
  121. */
  122. class Crypt_AES extends Crypt_Rijndael {
  123. /**
  124. * mcrypt resource for encryption
  125. *
  126. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  127. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  128. *
  129. * @see Crypt_AES::encrypt()
  130. * @var String
  131. * @access private
  132. */
  133. var $enmcrypt;
  134. /**
  135. * mcrypt resource for decryption
  136. *
  137. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  138. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  139. *
  140. * @see Crypt_AES::decrypt()
  141. * @var String
  142. * @access private
  143. */
  144. var $demcrypt;
  145. /**
  146. * mcrypt resource for CFB mode
  147. *
  148. * @see Crypt_AES::encrypt()
  149. * @see Crypt_AES::decrypt()
  150. * @var String
  151. * @access private
  152. */
  153. var $ecb;
  154. /**
  155. * Default Constructor.
  156. *
  157. * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be
  158. * CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC. If not explictly set, CRYPT_AES_MODE_CBC will be used.
  159. *
  160. * @param optional Integer $mode
  161. * @return Crypt_AES
  162. * @access public
  163. */
  164. function Crypt_AES($mode = CRYPT_AES_MODE_CBC)
  165. {
  166. if ( !defined('CRYPT_AES_MODE') ) {
  167. switch (true) {
  168. case extension_loaded('mcrypt') && in_array('rijndael-128', mcrypt_list_algorithms()):
  169. define('CRYPT_AES_MODE', CRYPT_AES_MODE_MCRYPT);
  170. break;
  171. default:
  172. define('CRYPT_AES_MODE', CRYPT_AES_MODE_INTERNAL);
  173. }
  174. }
  175. switch ( CRYPT_AES_MODE ) {
  176. case CRYPT_AES_MODE_MCRYPT:
  177. switch ($mode) {
  178. case CRYPT_AES_MODE_ECB:
  179. $this->paddable = true;
  180. $this->mode = MCRYPT_MODE_ECB;
  181. break;
  182. case CRYPT_AES_MODE_CTR:
  183. // ctr doesn't have a constant associated with it even though it appears to be fairly widely
  184. // supported. in lieu of knowing just how widely supported it is, i've, for now, opted not to
  185. // include a compatibility layer. the layer has been implemented but, for now, is commented out.
  186. $this->mode = 'ctr';
  187. //$this->mode = in_array('ctr', mcrypt_list_modes()) ? 'ctr' : CRYPT_AES_MODE_CTR;
  188. break;
  189. case CRYPT_AES_MODE_CFB:
  190. $this->mode = 'ncfb';
  191. break;
  192. case CRYPT_AES_MODE_OFB:
  193. $this->mode = MCRYPT_MODE_NOFB;
  194. break;
  195. case CRYPT_AES_MODE_CBC:
  196. default:
  197. $this->paddable = true;
  198. $this->mode = MCRYPT_MODE_CBC;
  199. }
  200. break;
  201. default:
  202. switch ($mode) {
  203. case CRYPT_AES_MODE_ECB:
  204. $this->paddable = true;
  205. $this->mode = CRYPT_RIJNDAEL_MODE_ECB;
  206. break;
  207. case CRYPT_AES_MODE_CTR:
  208. $this->mode = CRYPT_RIJNDAEL_MODE_CTR;
  209. break;
  210. case CRYPT_AES_MODE_CFB:
  211. $this->mode = CRYPT_RIJNDAEL_MODE_CFB;
  212. break;
  213. case CRYPT_AES_MODE_OFB:
  214. $this->mode = CRYPT_RIJNDAEL_MODE_OFB;
  215. break;
  216. case CRYPT_AES_MODE_CBC:
  217. default:
  218. $this->paddable = true;
  219. $this->mode = CRYPT_RIJNDAEL_MODE_CBC;
  220. }
  221. }
  222. if (CRYPT_AES_MODE == CRYPT_AES_MODE_INTERNAL) {
  223. parent::Crypt_Rijndael($this->mode);
  224. }
  225. }
  226. /**
  227. * Dummy function
  228. *
  229. * Since Crypt_AES extends Crypt_Rijndael, this function is, technically, available, but it doesn't do anything.
  230. *
  231. * @access public
  232. * @param Integer $length
  233. */
  234. function setBlockLength($length)
  235. {
  236. return;
  237. }
  238. /**
  239. * Sets the initialization vector. (optional)
  240. *
  241. * SetIV is not required when CRYPT_RIJNDAEL_MODE_ECB is being used. If not explictly set, it'll be assumed
  242. * to be all zero's.
  243. *
  244. * @access public
  245. * @param String $iv
  246. */
  247. function setIV($iv)
  248. {
  249. parent::setIV($iv);
  250. if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
  251. $this->changed = true;
  252. }
  253. }
  254. /**
  255. * Encrypts a message.
  256. *
  257. * $plaintext will be padded with up to 16 additional bytes. Other AES implementations may or may not pad in the
  258. * same manner. Other common approaches to padding and the reasons why it's necessary are discussed in the following
  259. * URL:
  260. *
  261. * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
  262. *
  263. * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
  264. * strlen($plaintext) will still need to be a multiple of 16, however, arbitrary values can be added to make it that
  265. * length.
  266. *
  267. * @see Crypt_AES::decrypt()
  268. * @access public
  269. * @param String $plaintext
  270. */
  271. function encrypt($plaintext)
  272. {
  273. if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
  274. $this->_mcryptSetup();
  275. // re: http://phpseclib.sourceforge.net/cfb-demo.phps
  276. // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
  277. // rewritten CFB implementation the above outputs the same thing twice.
  278. if ($this->mode == 'ncfb' && $this->continuousBuffer) {
  279. $iv = &$this->encryptIV;
  280. $pos = &$this->enbuffer['pos'];
  281. $len = strlen($plaintext);
  282. $ciphertext = '';
  283. $i = 0;
  284. if ($pos) {
  285. $orig_pos = $pos;
  286. $max = 16 - $pos;
  287. if ($len >= $max) {
  288. $i = $max;
  289. $len-= $max;
  290. $pos = 0;
  291. } else {
  292. $i = $len;
  293. $pos+= $len;
  294. $len = 0;
  295. }
  296. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  297. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  298. $this->enbuffer['enmcrypt_init'] = true;
  299. }
  300. if ($len >= 16) {
  301. if ($this->enbuffer['enmcrypt_init'] === false || $len > 280) {
  302. if ($this->enbuffer['enmcrypt_init'] === true) {
  303. mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
  304. $this->enbuffer['enmcrypt_init'] = false;
  305. }
  306. $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % 16));
  307. $iv = substr($ciphertext, -16);
  308. $len%= 16;
  309. } else {
  310. while ($len >= 16) {
  311. $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, 16);
  312. $ciphertext.= $iv;
  313. $len-= 16;
  314. $i+= 16;
  315. }
  316. }
  317. }
  318. if ($len) {
  319. $iv = mcrypt_generic($this->ecb, $iv);
  320. $block = $iv ^ substr($plaintext, -$len);
  321. $iv = substr_replace($iv, $block, 0, $len);
  322. $ciphertext.= $block;
  323. $pos = $len;
  324. }
  325. return $ciphertext;
  326. }
  327. if ($this->paddable) {
  328. $plaintext = $this->_pad($plaintext);
  329. }
  330. $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
  331. if (!$this->continuousBuffer) {
  332. mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
  333. }
  334. return $ciphertext;
  335. }
  336. return parent::encrypt($plaintext);
  337. }
  338. /**
  339. * Decrypts a message.
  340. *
  341. * If strlen($ciphertext) is not a multiple of 16, null bytes will be added to the end of the string until it is.
  342. *
  343. * @see Crypt_AES::encrypt()
  344. * @access public
  345. * @param String $ciphertext
  346. */
  347. function decrypt($ciphertext)
  348. {
  349. if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
  350. $this->_mcryptSetup();
  351. if ($this->mode == 'ncfb' && $this->continuousBuffer) {
  352. $iv = &$this->decryptIV;
  353. $pos = &$this->debuffer['pos'];
  354. $len = strlen($ciphertext);
  355. $plaintext = '';
  356. $i = 0;
  357. if ($pos) {
  358. $orig_pos = $pos;
  359. $max = 16 - $pos;
  360. if ($len >= $max) {
  361. $i = $max;
  362. $len-= $max;
  363. $pos = 0;
  364. } else {
  365. $i = $len;
  366. $pos+= $len;
  367. $len = 0;
  368. }
  369. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  370. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  371. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  372. }
  373. if ($len >= 16) {
  374. $cb = substr($ciphertext, $i, $len - $len % 16);
  375. $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
  376. $iv = substr($cb, -16);
  377. $len%= 16;
  378. }
  379. if ($len) {
  380. $iv = mcrypt_generic($this->ecb, $iv);
  381. $plaintext.= $iv ^ substr($ciphertext, -$len);
  382. $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
  383. $pos = $len;
  384. }
  385. return $plaintext;
  386. }
  387. if ($this->paddable) {
  388. // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
  389. // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
  390. $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 15) & 0xFFFFFFF0, chr(0));
  391. }
  392. $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
  393. if (!$this->continuousBuffer) {
  394. mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
  395. }
  396. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  397. }
  398. return parent::decrypt($ciphertext);
  399. }
  400. /**
  401. * Setup mcrypt
  402. *
  403. * Validates all the variables.
  404. *
  405. * @access private
  406. */
  407. function _mcryptSetup()
  408. {
  409. if (!$this->changed) {
  410. return;
  411. }
  412. if (!$this->explicit_key_length) {
  413. // this just copied from Crypt_Rijndael::_setup()
  414. $length = strlen($this->key) >> 2;
  415. if ($length > 8) {
  416. $length = 8;
  417. } else if ($length < 4) {
  418. $length = 4;
  419. }
  420. $this->Nk = $length;
  421. $this->key_size = $length << 2;
  422. }
  423. switch ($this->Nk) {
  424. case 4: // 128
  425. $this->key_size = 16;
  426. break;
  427. case 5: // 160
  428. case 6: // 192
  429. $this->key_size = 24;
  430. break;
  431. case 7: // 224
  432. case 8: // 256
  433. $this->key_size = 32;
  434. }
  435. $this->key = str_pad(substr($this->key, 0, $this->key_size), $this->key_size, chr(0));
  436. $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($this->iv, 0, 16), 16, chr(0));
  437. if (!isset($this->enmcrypt)) {
  438. $mode = $this->mode;
  439. //$mode = $this->mode == CRYPT_AES_MODE_CTR ? MCRYPT_MODE_ECB : $this->mode;
  440. $this->demcrypt = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mode, '');
  441. $this->enmcrypt = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mode, '');
  442. if ($mode == 'ncfb') {
  443. $this->ecb = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
  444. }
  445. } // else should mcrypt_generic_deinit be called?
  446. mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
  447. mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
  448. if ($this->mode == 'ncfb') {
  449. mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  450. }
  451. $this->changed = false;
  452. }
  453. /**
  454. * Treat consecutive "packets" as if they are a continuous buffer.
  455. *
  456. * The default behavior.
  457. *
  458. * @see Crypt_Rijndael::disableContinuousBuffer()
  459. * @access public
  460. */
  461. function enableContinuousBuffer()
  462. {
  463. parent::enableContinuousBuffer();
  464. if (CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT) {
  465. $this->enbuffer['enmcrypt_init'] = true;
  466. $this->debuffer['demcrypt_init'] = true;
  467. }
  468. }
  469. /**
  470. * Treat consecutive packets as if they are a discontinuous buffer.
  471. *
  472. * The default behavior.
  473. *
  474. * @see Crypt_Rijndael::enableContinuousBuffer()
  475. * @access public
  476. */
  477. function disableContinuousBuffer()
  478. {
  479. parent::disableContinuousBuffer();
  480. if (CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT) {
  481. mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
  482. mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
  483. }
  484. }
  485. }
  486. // vim: ts=4:sw=4:et:
  487. // vim6: fdl=1:
  488. ?>