AES.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. * Include Crypt_Rijndael
  65. */
  66. if (!class_exists('Crypt_Rijndael')) {
  67. require_once 'Rijndael.php';
  68. }
  69. /**#@+
  70. * @access public
  71. * @see Crypt_AES::encrypt()
  72. * @see Crypt_AES::decrypt()
  73. */
  74. /**
  75. * Encrypt / decrypt using the Counter mode.
  76. *
  77. * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
  78. *
  79. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
  80. */
  81. define('CRYPT_AES_MODE_CTR', -1);
  82. /**
  83. * Encrypt / decrypt using the Electronic Code Book mode.
  84. *
  85. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
  86. */
  87. define('CRYPT_AES_MODE_ECB', 1);
  88. /**
  89. * Encrypt / decrypt using the Code Book Chaining mode.
  90. *
  91. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
  92. */
  93. define('CRYPT_AES_MODE_CBC', 2);
  94. /**
  95. * Encrypt / decrypt using the Cipher Feedback mode.
  96. *
  97. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
  98. */
  99. define('CRYPT_AES_MODE_CFB', 3);
  100. /**
  101. * Encrypt / decrypt using the Cipher Feedback mode.
  102. *
  103. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
  104. */
  105. define('CRYPT_AES_MODE_OFB', 4);
  106. /**#@-*/
  107. /**#@+
  108. * @access private
  109. * @see Crypt_AES::Crypt_AES()
  110. */
  111. /**
  112. * Toggles the internal implementation
  113. */
  114. define('CRYPT_AES_MODE_INTERNAL', 1);
  115. /**
  116. * Toggles the mcrypt implementation
  117. */
  118. define('CRYPT_AES_MODE_MCRYPT', 2);
  119. /**#@-*/
  120. /**
  121. * Pure-PHP implementation of AES.
  122. *
  123. * @author Jim Wigginton <terrafrost@php.net>
  124. * @version 0.1.0
  125. * @access public
  126. * @package Crypt_AES
  127. */
  128. class Crypt_AES extends Crypt_Rijndael {
  129. /**
  130. * mcrypt resource for encryption
  131. *
  132. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  133. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  134. *
  135. * @see Crypt_AES::encrypt()
  136. * @var String
  137. * @access private
  138. */
  139. var $enmcrypt;
  140. /**
  141. * mcrypt resource for decryption
  142. *
  143. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  144. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  145. *
  146. * @see Crypt_AES::decrypt()
  147. * @var String
  148. * @access private
  149. */
  150. var $demcrypt;
  151. /**
  152. * mcrypt resource for CFB mode
  153. *
  154. * @see Crypt_AES::encrypt()
  155. * @see Crypt_AES::decrypt()
  156. * @var String
  157. * @access private
  158. */
  159. var $ecb;
  160. /**
  161. * Default Constructor.
  162. *
  163. * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be
  164. * CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC. If not explictly set, CRYPT_AES_MODE_CBC will be used.
  165. *
  166. * @param optional Integer $mode
  167. * @return Crypt_AES
  168. * @access public
  169. */
  170. function Crypt_AES($mode = CRYPT_AES_MODE_CBC)
  171. {
  172. if ( !defined('CRYPT_AES_MODE') ) {
  173. switch (true) {
  174. case extension_loaded('mcrypt') && in_array('rijndael-128', mcrypt_list_algorithms()):
  175. define('CRYPT_AES_MODE', CRYPT_AES_MODE_MCRYPT);
  176. break;
  177. default:
  178. define('CRYPT_AES_MODE', CRYPT_AES_MODE_INTERNAL);
  179. }
  180. }
  181. switch ( CRYPT_AES_MODE ) {
  182. case CRYPT_AES_MODE_MCRYPT:
  183. switch ($mode) {
  184. case CRYPT_AES_MODE_ECB:
  185. $this->paddable = true;
  186. $this->mode = MCRYPT_MODE_ECB;
  187. break;
  188. case CRYPT_AES_MODE_CTR:
  189. // ctr doesn't have a constant associated with it even though it appears to be fairly widely
  190. // supported. in lieu of knowing just how widely supported it is, i've, for now, opted not to
  191. // include a compatibility layer. the layer has been implemented but, for now, is commented out.
  192. $this->mode = 'ctr';
  193. //$this->mode = in_array('ctr', mcrypt_list_modes()) ? 'ctr' : CRYPT_AES_MODE_CTR;
  194. break;
  195. case CRYPT_AES_MODE_CFB:
  196. $this->mode = 'ncfb';
  197. break;
  198. case CRYPT_AES_MODE_OFB:
  199. $this->mode = MCRYPT_MODE_NOFB;
  200. break;
  201. case CRYPT_AES_MODE_CBC:
  202. default:
  203. $this->paddable = true;
  204. $this->mode = MCRYPT_MODE_CBC;
  205. }
  206. break;
  207. default:
  208. switch ($mode) {
  209. case CRYPT_AES_MODE_ECB:
  210. $this->paddable = true;
  211. $this->mode = CRYPT_RIJNDAEL_MODE_ECB;
  212. break;
  213. case CRYPT_AES_MODE_CTR:
  214. $this->mode = CRYPT_RIJNDAEL_MODE_CTR;
  215. break;
  216. case CRYPT_AES_MODE_CFB:
  217. $this->mode = CRYPT_RIJNDAEL_MODE_CFB;
  218. break;
  219. case CRYPT_AES_MODE_OFB:
  220. $this->mode = CRYPT_RIJNDAEL_MODE_OFB;
  221. break;
  222. case CRYPT_AES_MODE_CBC:
  223. default:
  224. $this->paddable = true;
  225. $this->mode = CRYPT_RIJNDAEL_MODE_CBC;
  226. }
  227. }
  228. if (CRYPT_AES_MODE == CRYPT_AES_MODE_INTERNAL) {
  229. parent::Crypt_Rijndael($this->mode);
  230. }
  231. }
  232. /**
  233. * Dummy function
  234. *
  235. * Since Crypt_AES extends Crypt_Rijndael, this function is, technically, available, but it doesn't do anything.
  236. *
  237. * @access public
  238. * @param Integer $length
  239. */
  240. function setBlockLength($length)
  241. {
  242. return;
  243. }
  244. /**
  245. * Sets the initialization vector. (optional)
  246. *
  247. * SetIV is not required when CRYPT_RIJNDAEL_MODE_ECB is being used. If not explictly set, it'll be assumed
  248. * to be all zero's.
  249. *
  250. * @access public
  251. * @param String $iv
  252. */
  253. function setIV($iv)
  254. {
  255. parent::setIV($iv);
  256. if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
  257. $this->changed = true;
  258. }
  259. }
  260. /**
  261. * Encrypts a message.
  262. *
  263. * $plaintext will be padded with up to 16 additional bytes. Other AES implementations may or may not pad in the
  264. * same manner. Other common approaches to padding and the reasons why it's necessary are discussed in the following
  265. * URL:
  266. *
  267. * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
  268. *
  269. * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
  270. * strlen($plaintext) will still need to be a multiple of 16, however, arbitrary values can be added to make it that
  271. * length.
  272. *
  273. * @see Crypt_AES::decrypt()
  274. * @access public
  275. * @param String $plaintext
  276. */
  277. function encrypt($plaintext)
  278. {
  279. if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
  280. $this->_mcryptSetup();
  281. // re: http://phpseclib.sourceforge.net/cfb-demo.phps
  282. // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
  283. // rewritten CFB implementation the above outputs the same thing twice.
  284. if ($this->mode == 'ncfb' && $this->continuousBuffer) {
  285. $iv = &$this->encryptIV;
  286. $pos = &$this->enbuffer['pos'];
  287. $len = strlen($plaintext);
  288. $ciphertext = '';
  289. $i = 0;
  290. if ($pos) {
  291. $orig_pos = $pos;
  292. $max = 16 - $pos;
  293. if ($len >= $max) {
  294. $i = $max;
  295. $len-= $max;
  296. $pos = 0;
  297. } else {
  298. $i = $len;
  299. $pos+= $len;
  300. $len = 0;
  301. }
  302. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  303. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  304. $this->enbuffer['enmcrypt_init'] = true;
  305. }
  306. if ($len >= 16) {
  307. if ($this->enbuffer['enmcrypt_init'] === false || $len > 280) {
  308. if ($this->enbuffer['enmcrypt_init'] === true) {
  309. mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
  310. $this->enbuffer['enmcrypt_init'] = false;
  311. }
  312. $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % 16));
  313. $iv = substr($ciphertext, -16);
  314. $len%= 16;
  315. } else {
  316. while ($len >= 16) {
  317. $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, 16);
  318. $ciphertext.= $iv;
  319. $len-= 16;
  320. $i+= 16;
  321. }
  322. }
  323. }
  324. if ($len) {
  325. $iv = mcrypt_generic($this->ecb, $iv);
  326. $block = $iv ^ substr($plaintext, -$len);
  327. $iv = substr_replace($iv, $block, 0, $len);
  328. $ciphertext.= $block;
  329. $pos = $len;
  330. }
  331. return $ciphertext;
  332. }
  333. if ($this->paddable) {
  334. $plaintext = $this->_pad($plaintext);
  335. }
  336. $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
  337. if (!$this->continuousBuffer) {
  338. mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
  339. }
  340. return $ciphertext;
  341. }
  342. return parent::encrypt($plaintext);
  343. }
  344. /**
  345. * Decrypts a message.
  346. *
  347. * If strlen($ciphertext) is not a multiple of 16, null bytes will be added to the end of the string until it is.
  348. *
  349. * @see Crypt_AES::encrypt()
  350. * @access public
  351. * @param String $ciphertext
  352. */
  353. function decrypt($ciphertext)
  354. {
  355. if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
  356. $this->_mcryptSetup();
  357. if ($this->mode == 'ncfb' && $this->continuousBuffer) {
  358. $iv = &$this->decryptIV;
  359. $pos = &$this->debuffer['pos'];
  360. $len = strlen($ciphertext);
  361. $plaintext = '';
  362. $i = 0;
  363. if ($pos) {
  364. $orig_pos = $pos;
  365. $max = 16 - $pos;
  366. if ($len >= $max) {
  367. $i = $max;
  368. $len-= $max;
  369. $pos = 0;
  370. } else {
  371. $i = $len;
  372. $pos+= $len;
  373. $len = 0;
  374. }
  375. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  376. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  377. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  378. }
  379. if ($len >= 16) {
  380. $cb = substr($ciphertext, $i, $len - $len % 16);
  381. $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
  382. $iv = substr($cb, -16);
  383. $len%= 16;
  384. }
  385. if ($len) {
  386. $iv = mcrypt_generic($this->ecb, $iv);
  387. $plaintext.= $iv ^ substr($ciphertext, -$len);
  388. $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
  389. $pos = $len;
  390. }
  391. return $plaintext;
  392. }
  393. if ($this->paddable) {
  394. // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
  395. // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
  396. $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 15) & 0xFFFFFFF0, chr(0));
  397. }
  398. $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
  399. if (!$this->continuousBuffer) {
  400. mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
  401. }
  402. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  403. }
  404. return parent::decrypt($ciphertext);
  405. }
  406. /**
  407. * Setup mcrypt
  408. *
  409. * Validates all the variables.
  410. *
  411. * @access private
  412. */
  413. function _mcryptSetup()
  414. {
  415. if (!$this->changed) {
  416. return;
  417. }
  418. if (!$this->explicit_key_length) {
  419. // this just copied from Crypt_Rijndael::_setup()
  420. $length = strlen($this->key) >> 2;
  421. if ($length > 8) {
  422. $length = 8;
  423. } else if ($length < 4) {
  424. $length = 4;
  425. }
  426. $this->Nk = $length;
  427. $this->key_size = $length << 2;
  428. }
  429. switch ($this->Nk) {
  430. case 4: // 128
  431. $this->key_size = 16;
  432. break;
  433. case 5: // 160
  434. case 6: // 192
  435. $this->key_size = 24;
  436. break;
  437. case 7: // 224
  438. case 8: // 256
  439. $this->key_size = 32;
  440. }
  441. $this->key = str_pad(substr($this->key, 0, $this->key_size), $this->key_size, chr(0));
  442. $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($this->iv, 0, 16), 16, chr(0));
  443. if (!isset($this->enmcrypt)) {
  444. $mode = $this->mode;
  445. //$mode = $this->mode == CRYPT_AES_MODE_CTR ? MCRYPT_MODE_ECB : $this->mode;
  446. $this->demcrypt = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mode, '');
  447. $this->enmcrypt = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mode, '');
  448. if ($mode == 'ncfb') {
  449. $this->ecb = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
  450. }
  451. } // else should mcrypt_generic_deinit be called?
  452. mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
  453. mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
  454. if ($this->mode == 'ncfb') {
  455. mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  456. }
  457. $this->changed = false;
  458. }
  459. /**
  460. * Treat consecutive "packets" as if they are a continuous buffer.
  461. *
  462. * The default behavior.
  463. *
  464. * @see Crypt_Rijndael::disableContinuousBuffer()
  465. * @access public
  466. */
  467. function enableContinuousBuffer()
  468. {
  469. parent::enableContinuousBuffer();
  470. if (CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT) {
  471. $this->enbuffer['enmcrypt_init'] = true;
  472. $this->debuffer['demcrypt_init'] = true;
  473. }
  474. }
  475. /**
  476. * Treat consecutive packets as if they are a discontinuous buffer.
  477. *
  478. * The default behavior.
  479. *
  480. * @see Crypt_Rijndael::enableContinuousBuffer()
  481. * @access public
  482. */
  483. function disableContinuousBuffer()
  484. {
  485. parent::disableContinuousBuffer();
  486. if (CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT) {
  487. mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
  488. mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
  489. }
  490. }
  491. }
  492. // vim: ts=4:sw=4:et:
  493. // vim6: fdl=1: