RC4.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Pure-PHP implementation of RC4.
  5. *
  6. * Uses mcrypt, if available, and an internal implementation, otherwise.
  7. *
  8. * PHP versions 4 and 5
  9. *
  10. * Useful resources are as follows:
  11. *
  12. * - {@link http://www.mozilla.org/projects/security/pki/nss/draft-kaukonen-cipher-arcfour-03.txt ARCFOUR Algorithm}
  13. * - {@link http://en.wikipedia.org/wiki/RC4 - Wikipedia: RC4}
  14. *
  15. * RC4 is also known as ARCFOUR or ARC4. The reason is elaborated upon at Wikipedia. This class is named RC4 and not
  16. * ARCFOUR or ARC4 because RC4 is how it is refered to in the SSH1 specification.
  17. *
  18. * Here's a short example of how to use this library:
  19. * <code>
  20. * <?php
  21. * include('Crypt/RC4.php');
  22. *
  23. * $rc4 = new Crypt_RC4();
  24. *
  25. * $rc4->setKey('abcdefgh');
  26. *
  27. * $size = 10 * 1024;
  28. * $plaintext = '';
  29. * for ($i = 0; $i < $size; $i++) {
  30. * $plaintext.= 'a';
  31. * }
  32. *
  33. * echo $rc4->decrypt($rc4->encrypt($plaintext));
  34. * ?>
  35. * </code>
  36. *
  37. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  38. * of this software and associated documentation files (the "Software"), to deal
  39. * in the Software without restriction, including without limitation the rights
  40. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41. * copies of the Software, and to permit persons to whom the Software is
  42. * furnished to do so, subject to the following conditions:
  43. *
  44. * The above copyright notice and this permission notice shall be included in
  45. * all copies or substantial portions of the Software.
  46. *
  47. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  48. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  49. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  50. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  51. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  52. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  53. * THE SOFTWARE.
  54. *
  55. * @category Crypt
  56. * @package Crypt_RC4
  57. * @author Jim Wigginton <terrafrost@php.net>
  58. * @copyright MMVII Jim Wigginton
  59. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  60. * @version $Id: RC4.php,v 1.8 2009/06/09 04:00:38 terrafrost Exp $
  61. * @link http://phpseclib.sourceforge.net
  62. */
  63. /**#@+
  64. * @access private
  65. * @see Crypt_RC4::Crypt_RC4()
  66. */
  67. /**
  68. * Toggles the internal implementation
  69. */
  70. define('CRYPT_RC4_MODE_INTERNAL', 1);
  71. /**
  72. * Toggles the mcrypt implementation
  73. */
  74. define('CRYPT_RC4_MODE_MCRYPT', 2);
  75. /**#@-*/
  76. /**#@+
  77. * @access private
  78. * @see Crypt_RC4::_crypt()
  79. */
  80. define('CRYPT_RC4_ENCRYPT', 0);
  81. define('CRYPT_RC4_DECRYPT', 1);
  82. /**#@-*/
  83. /**
  84. * Pure-PHP implementation of RC4.
  85. *
  86. * @author Jim Wigginton <terrafrost@php.net>
  87. * @version 0.1.0
  88. * @access public
  89. * @package Crypt_RC4
  90. */
  91. class Crypt_RC4 {
  92. /**
  93. * The Key
  94. *
  95. * @see Crypt_RC4::setKey()
  96. * @var String
  97. * @access private
  98. */
  99. var $key = "\0";
  100. /**
  101. * The Key Stream for encryption
  102. *
  103. * If CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT, this will be equal to the mcrypt object
  104. *
  105. * @see Crypt_RC4::setKey()
  106. * @var Array
  107. * @access private
  108. */
  109. var $encryptStream = false;
  110. /**
  111. * The Key Stream for decryption
  112. *
  113. * If CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT, this will be equal to the mcrypt object
  114. *
  115. * @see Crypt_RC4::setKey()
  116. * @var Array
  117. * @access private
  118. */
  119. var $decryptStream = false;
  120. /**
  121. * The $i and $j indexes for encryption
  122. *
  123. * @see Crypt_RC4::_crypt()
  124. * @var Integer
  125. * @access private
  126. */
  127. var $encryptIndex = 0;
  128. /**
  129. * The $i and $j indexes for decryption
  130. *
  131. * @see Crypt_RC4::_crypt()
  132. * @var Integer
  133. * @access private
  134. */
  135. var $decryptIndex = 0;
  136. /**
  137. * MCrypt parameters
  138. *
  139. * @see Crypt_RC4::setMCrypt()
  140. * @var Array
  141. * @access private
  142. */
  143. var $mcrypt = array('', '');
  144. /**
  145. * The Encryption Algorithm
  146. *
  147. * Only used if CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT. Only possible values are MCRYPT_RC4 or MCRYPT_ARCFOUR.
  148. *
  149. * @see Crypt_RC4::Crypt_RC4()
  150. * @var Integer
  151. * @access private
  152. */
  153. var $mode;
  154. /**
  155. * Continuous Buffer status
  156. *
  157. * @see Crypt_RC4::enableContinuousBuffer()
  158. * @var Boolean
  159. * @access private
  160. */
  161. var $continuousBuffer = false;
  162. /**
  163. * Default Constructor.
  164. *
  165. * Determines whether or not the mcrypt extension should be used.
  166. *
  167. * @param optional Integer $mode
  168. * @return Crypt_RC4
  169. * @access public
  170. */
  171. function Crypt_RC4()
  172. {
  173. if ( !defined('CRYPT_RC4_MODE') ) {
  174. switch (true) {
  175. case extension_loaded('mcrypt') && (defined('MCRYPT_ARCFOUR') || defined('MCRYPT_RC4')):
  176. // i'd check to see if rc4 was supported, by doing in_array('arcfour', mcrypt_list_algorithms('')),
  177. // but since that can be changed after the object has been created, there doesn't seem to be
  178. // a lot of point...
  179. define('CRYPT_RC4_MODE', CRYPT_RC4_MODE_MCRYPT);
  180. break;
  181. default:
  182. define('CRYPT_RC4_MODE', CRYPT_RC4_MODE_INTERNAL);
  183. }
  184. }
  185. switch ( CRYPT_RC4_MODE ) {
  186. case CRYPT_RC4_MODE_MCRYPT:
  187. switch (true) {
  188. case defined('MCRYPT_ARCFOUR'):
  189. $this->mode = MCRYPT_ARCFOUR;
  190. break;
  191. case defined('MCRYPT_RC4');
  192. $this->mode = MCRYPT_RC4;
  193. }
  194. }
  195. }
  196. /**
  197. * Sets the key.
  198. *
  199. * Keys can be between 1 and 256 bytes long. If they are longer then 256 bytes, the first 256 bytes will
  200. * be used. If no key is explicitly set, it'll be assumed to be a single null byte.
  201. *
  202. * @access public
  203. * @param String $key
  204. */
  205. function setKey($key)
  206. {
  207. $this->key = $key;
  208. if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
  209. return;
  210. }
  211. $keyLength = strlen($key);
  212. $keyStream = array();
  213. for ($i = 0; $i < 256; $i++) {
  214. $keyStream[$i] = $i;
  215. }
  216. $j = 0;
  217. for ($i = 0; $i < 256; $i++) {
  218. $j = ($j + $keyStream[$i] + ord($key[$i % $keyLength])) & 255;
  219. $temp = $keyStream[$i];
  220. $keyStream[$i] = $keyStream[$j];
  221. $keyStream[$j] = $temp;
  222. }
  223. $this->encryptIndex = $this->decryptIndex = array(0, 0);
  224. $this->encryptStream = $this->decryptStream = $keyStream;
  225. }
  226. /**
  227. * Dummy function.
  228. *
  229. * Some protocols, such as WEP, prepend an "initialization vector" to the key, effectively creating a new key [1].
  230. * If you need to use an initialization vector in this manner, feel free to prepend it to the key, yourself, before
  231. * calling setKey().
  232. *
  233. * [1] WEP's initialization vectors (IV's) are used in a somewhat insecure way. Since, in that protocol,
  234. * the IV's are relatively easy to predict, an attack described by
  235. * {@link http://www.drizzle.com/~aboba/IEEE/rc4_ksaproc.pdf Scott Fluhrer, Itsik Mantin, and Adi Shamir}
  236. * can be used to quickly guess at the rest of the key. The following links elaborate:
  237. *
  238. * {@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009}
  239. * {@link http://en.wikipedia.org/wiki/Related_key_attack http://en.wikipedia.org/wiki/Related_key_attack}
  240. *
  241. * @param String $iv
  242. * @see Crypt_RC4::setKey()
  243. * @access public
  244. */
  245. function setIV($iv)
  246. {
  247. }
  248. /**
  249. * Sets MCrypt parameters. (optional)
  250. *
  251. * If MCrypt is being used, empty strings will be used, unless otherwise specified.
  252. *
  253. * @link http://php.net/function.mcrypt-module-open#function.mcrypt-module-open
  254. * @access public
  255. * @param optional Integer $algorithm_directory
  256. * @param optional Integer $mode_directory
  257. */
  258. function setMCrypt($algorithm_directory = '', $mode_directory = '')
  259. {
  260. if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
  261. $this->mcrypt = array($algorithm_directory, $mode_directory);
  262. $this->_closeMCrypt();
  263. }
  264. }
  265. /**
  266. * Encrypts a message.
  267. *
  268. * @see Crypt_RC4::_crypt()
  269. * @access public
  270. * @param String $plaintext
  271. */
  272. function encrypt($plaintext)
  273. {
  274. return $this->_crypt($plaintext, CRYPT_RC4_ENCRYPT);
  275. }
  276. /**
  277. * Decrypts a message.
  278. *
  279. * $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)).
  280. * Atleast if the continuous buffer is disabled.
  281. *
  282. * @see Crypt_RC4::_crypt()
  283. * @access public
  284. * @param String $ciphertext
  285. */
  286. function decrypt($ciphertext)
  287. {
  288. return $this->_crypt($ciphertext, CRYPT_RC4_DECRYPT);
  289. }
  290. /**
  291. * Encrypts or decrypts a message.
  292. *
  293. * @see Crypt_RC4::encrypt()
  294. * @see Crypt_RC4::decrypt()
  295. * @access private
  296. * @param String $text
  297. * @param Integer $mode
  298. */
  299. function _crypt($text, $mode)
  300. {
  301. if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
  302. $keyStream = $mode == CRYPT_RC4_ENCRYPT ? 'encryptStream' : 'decryptStream';
  303. if ($this->$keyStream === false) {
  304. $this->$keyStream = mcrypt_module_open($this->mode, $this->mcrypt[0], MCRYPT_MODE_STREAM, $this->mcrypt[1]);
  305. mcrypt_generic_init($this->$keyStream, $this->key, '');
  306. } else if (!$this->continuousBuffer) {
  307. mcrypt_generic_init($this->$keyStream, $this->key, '');
  308. }
  309. $newText = mcrypt_generic($this->$keyStream, $text);
  310. if (!$this->continuousBuffer) {
  311. mcrypt_generic_deinit($this->$keyStream);
  312. }
  313. return $newText;
  314. }
  315. if ($this->encryptStream === false) {
  316. $this->setKey($this->key);
  317. }
  318. switch ($mode) {
  319. case CRYPT_RC4_ENCRYPT:
  320. $keyStream = $this->encryptStream;
  321. list($i, $j) = $this->encryptIndex;
  322. break;
  323. case CRYPT_RC4_DECRYPT:
  324. $keyStream = $this->decryptStream;
  325. list($i, $j) = $this->decryptIndex;
  326. }
  327. $newText = '';
  328. for ($k = 0; $k < strlen($text); $k++) {
  329. $i = ($i + 1) & 255;
  330. $j = ($j + $keyStream[$i]) & 255;
  331. $temp = $keyStream[$i];
  332. $keyStream[$i] = $keyStream[$j];
  333. $keyStream[$j] = $temp;
  334. $temp = $keyStream[($keyStream[$i] + $keyStream[$j]) & 255];
  335. $newText.= chr(ord($text[$k]) ^ $temp);
  336. }
  337. if ($this->continuousBuffer) {
  338. switch ($mode) {
  339. case CRYPT_RC4_ENCRYPT:
  340. $this->encryptStream = $keyStream;
  341. $this->encryptIndex = array($i, $j);
  342. break;
  343. case CRYPT_RC4_DECRYPT:
  344. $this->decryptStream = $keyStream;
  345. $this->decryptIndex = array($i, $j);
  346. }
  347. }
  348. return $newText;
  349. }
  350. /**
  351. * Treat consecutive "packets" as if they are a continuous buffer.
  352. *
  353. * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
  354. * will yield different outputs:
  355. *
  356. * <code>
  357. * echo $rc4->encrypt(substr($plaintext, 0, 8));
  358. * echo $rc4->encrypt(substr($plaintext, 8, 8));
  359. * </code>
  360. * <code>
  361. * echo $rc4->encrypt($plaintext);
  362. * </code>
  363. *
  364. * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
  365. * another, as demonstrated with the following:
  366. *
  367. * <code>
  368. * $rc4->encrypt(substr($plaintext, 0, 8));
  369. * echo $rc4->decrypt($des->encrypt(substr($plaintext, 8, 8)));
  370. * </code>
  371. * <code>
  372. * echo $rc4->decrypt($des->encrypt(substr($plaintext, 8, 8)));
  373. * </code>
  374. *
  375. * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
  376. * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
  377. * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
  378. *
  379. * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
  380. * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
  381. * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
  382. * however, they are also less intuitive and more likely to cause you problems.
  383. *
  384. * @see Crypt_RC4::disableContinuousBuffer()
  385. * @access public
  386. */
  387. function enableContinuousBuffer()
  388. {
  389. $this->continuousBuffer = true;
  390. }
  391. /**
  392. * Treat consecutive packets as if they are a discontinuous buffer.
  393. *
  394. * The default behavior.
  395. *
  396. * @see Crypt_RC4::enableContinuousBuffer()
  397. * @access public
  398. */
  399. function disableContinuousBuffer()
  400. {
  401. if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_INTERNAL ) {
  402. $this->encryptIndex = $this->decryptIndex = array(0, 0);
  403. $this->setKey($this->key);
  404. }
  405. $this->continuousBuffer = false;
  406. }
  407. /**
  408. * Dummy function.
  409. *
  410. * Since RC4 is a stream cipher and not a block cipher, no padding is necessary. The only reason this function is
  411. * included is so that you can switch between a block cipher and a stream cipher transparently.
  412. *
  413. * @see Crypt_RC4::disablePadding()
  414. * @access public
  415. */
  416. function enablePadding()
  417. {
  418. }
  419. /**
  420. * Dummy function.
  421. *
  422. * @see Crypt_RC4::enablePadding()
  423. * @access public
  424. */
  425. function disablePadding()
  426. {
  427. }
  428. /**
  429. * Class destructor.
  430. *
  431. * Will be called, automatically, if you're using PHP5. If you're using PHP4, call it yourself. Only really
  432. * needs to be called if mcrypt is being used.
  433. *
  434. * @access public
  435. */
  436. function __destruct()
  437. {
  438. if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
  439. $this->_closeMCrypt();
  440. }
  441. }
  442. /**
  443. * Properly close the MCrypt objects.
  444. *
  445. * @access prviate
  446. */
  447. function _closeMCrypt()
  448. {
  449. if ( $this->encryptStream !== false ) {
  450. if ( $this->continuousBuffer ) {
  451. mcrypt_generic_deinit($this->encryptStream);
  452. }
  453. mcrypt_module_close($this->encryptStream);
  454. $this->encryptStream = false;
  455. }
  456. if ( $this->decryptStream !== false ) {
  457. if ( $this->continuousBuffer ) {
  458. mcrypt_generic_deinit($this->decryptStream);
  459. }
  460. mcrypt_module_close($this->decryptStream);
  461. $this->decryptStream = false;
  462. }
  463. }
  464. }