2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
5 * Pure-PHP implementation of RC4.
7 * Uses mcrypt, if available, and an internal implementation, otherwise.
11 * Useful resources are as follows:
13 * - {@link http://www.mozilla.org/projects/security/pki/nss/draft-kaukonen-cipher-arcfour-03.txt ARCFOUR Algorithm}
14 * - {@link http://en.wikipedia.org/wiki/RC4 - Wikipedia: RC4}
16 * RC4 is also known as ARCFOUR or ARC4. The reason is elaborated upon at Wikipedia. This class is named RC4 and not
17 * ARCFOUR or ARC4 because RC4 is how it is refered to in the SSH1 specification.
19 * Here's a short example of how to use this library:
22 * include('Crypt/RC4.php');
24 * $rc4 = new Crypt_RC4();
26 * $rc4->setKey('abcdefgh');
30 * for ($i = 0; $i < $size; $i++) {
34 * echo $rc4->decrypt($rc4->encrypt($plaintext));
38 * LICENSE: This library is free software; you can redistribute it and/or
39 * modify it under the terms of the GNU Lesser General Public
40 * License as published by the Free Software Foundation; either
41 * version 2.1 of the License, or (at your option) any later version.
43 * This library is distributed in the hope that it will be useful,
44 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
46 * Lesser General Public License for more details.
48 * You should have received a copy of the GNU Lesser General Public
49 * License along with this library; if not, write to the Free Software
50 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
55 * @author Jim Wigginton <terrafrost@php.net>
56 * @copyright MMVII Jim Wigginton
57 * @license http://www.gnu.org/licenses/lgpl.txt
58 * @version $Id: RC4.php,v 1.8 2009/06/09 04:00:38 terrafrost Exp $
59 * @link http://phpseclib.sourceforge.net
64 * @see Crypt_RC4::Crypt_RC4()
67 * Toggles the internal implementation
69 define('CRYPT_RC4_MODE_INTERNAL', 1);
71 * Toggles the mcrypt implementation
73 define('CRYPT_RC4_MODE_MCRYPT', 2);
78 * @see Crypt_RC4::_crypt()
80 define('CRYPT_RC4_ENCRYPT', 0);
81 define('CRYPT_RC4_DECRYPT', 1);
85 * Pure-PHP implementation of RC4.
87 * @author Jim Wigginton <terrafrost@php.net>
96 * @see Crypt_RC4::setKey()
103 * The Key Stream for encryption
105 * If CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT, this will be equal to the mcrypt object
107 * @see Crypt_RC4::setKey()
111 var $encryptStream = false;
114 * The Key Stream for decryption
116 * If CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT, this will be equal to the mcrypt object
118 * @see Crypt_RC4::setKey()
122 var $decryptStream = false;
125 * The $i and $j indexes for encryption
127 * @see Crypt_RC4::_crypt()
131 var $encryptIndex = 0;
134 * The $i and $j indexes for decryption
136 * @see Crypt_RC4::_crypt()
140 var $decryptIndex = 0;
145 * @see Crypt_RC4::setMCrypt()
149 var $mcrypt = array('', '');
152 * The Encryption Algorithm
154 * Only used if CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT. Only possible values are MCRYPT_RC4 or MCRYPT_ARCFOUR.
156 * @see Crypt_RC4::Crypt_RC4()
163 * Default Constructor.
165 * Determines whether or not the mcrypt extension should be used.
167 * @param optional Integer $mode
173 if ( !defined('CRYPT_RC4_MODE') ) {
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
179 define('CRYPT_RC4_MODE', CRYPT_RC4_MODE_MCRYPT);
182 define('CRYPT_RC4_MODE', CRYPT_RC4_MODE_INTERNAL);
186 switch ( CRYPT_RC4_MODE ) {
187 case CRYPT_RC4_MODE_MCRYPT:
189 case defined('MCRYPT_ARCFOUR'):
190 $this->mode = MCRYPT_ARCFOUR;
192 case defined('MCRYPT_RC4');
193 $this->mode = MCRYPT_RC4;
201 * Keys can be between 1 and 256 bytes long. If they are longer then 256 bytes, the first 256 bytes will
202 * be used. If no key is explicitly set, it'll be assumed to be a single null byte.
207 function setKey($key)
211 if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
215 $keyLength = strlen($key);
216 $keyStream = array();
217 for ($i = 0; $i < 256; $i++) {
221 for ($i = 0; $i < 256; $i++) {
222 $j = ($j + $keyStream[$i] + ord($key[$i % $keyLength])) & 255;
223 $temp = $keyStream[$i];
224 $keyStream[$i] = $keyStream[$j];
225 $keyStream[$j] = $temp;
228 $this->encryptIndex = $this->decryptIndex = array(0, 0);
229 $this->encryptStream = $this->decryptStream = $keyStream;
235 * Some protocols, such as WEP, prepend an "initialization vector" to the key, effectively creating a new key [1].
236 * If you need to use an initialization vector in this manner, feel free to prepend it to the key, yourself, before
239 * [1] WEP's initialization vectors (IV's) are used in a somewhat insecure way. Since, in that protocol,
240 * the IV's are relatively easy to predict, an attack described by
241 * {@link http://www.drizzle.com/~aboba/IEEE/rc4_ksaproc.pdf Scott Fluhrer, Itsik Mantin, and Adi Shamir}
242 * can be used to quickly guess at the rest of the key. The following links elaborate:
244 * {@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009}
245 * {@link http://en.wikipedia.org/wiki/Related_key_attack http://en.wikipedia.org/wiki/Related_key_attack}
248 * @see Crypt_RC4::setKey()
256 * Sets MCrypt parameters. (optional)
258 * If MCrypt is being used, empty strings will be used, unless otherwise specified.
260 * @link http://php.net/function.mcrypt-module-open#function.mcrypt-module-open
262 * @param optional Integer $algorithm_directory
263 * @param optional Integer $mode_directory
265 function setMCrypt($algorithm_directory = '', $mode_directory = '')
267 if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
268 $this->mcrypt = array($algorithm_directory, $mode_directory);
269 $this->_closeMCrypt();
274 * Encrypts a message.
276 * @see Crypt_RC4::_crypt()
278 * @param String $plaintext
280 function encrypt($plaintext)
282 return $this->_crypt($plaintext, CRYPT_RC4_ENCRYPT);
286 * Decrypts a message.
288 * $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)).
289 * Atleast if the continuous buffer is disabled.
291 * @see Crypt_RC4::_crypt()
293 * @param String $ciphertext
295 function decrypt($ciphertext)
297 return $this->_crypt($ciphertext, CRYPT_RC4_DECRYPT);
301 * Encrypts or decrypts a message.
303 * @see Crypt_RC4::encrypt()
304 * @see Crypt_RC4::decrypt()
306 * @param String $text
307 * @param Integer $mode
309 function _crypt($text, $mode)
311 if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
312 $keyStream = $mode == CRYPT_RC4_ENCRYPT ? 'encryptStream' : 'decryptStream';
314 if ($this->$keyStream === false) {
315 $this->$keyStream = mcrypt_module_open($this->mode, $this->mcrypt[0], MCRYPT_MODE_STREAM, $this->mcrypt[1]);
316 mcrypt_generic_init($this->$keyStream, $this->key, '');
317 } else if (!$this->continuousBuffer) {
318 mcrypt_generic_init($this->$keyStream, $this->key, '');
320 $newText = mcrypt_generic($this->$keyStream, $text);
321 if (!$this->continuousBuffer) {
322 mcrypt_generic_deinit($this->$keyStream);
328 if ($this->encryptStream === false) {
329 $this->setKey($this->key);
333 case CRYPT_RC4_ENCRYPT:
334 $keyStream = $this->encryptStream;
335 list($i, $j) = $this->encryptIndex;
337 case CRYPT_RC4_DECRYPT:
338 $keyStream = $this->decryptStream;
339 list($i, $j) = $this->decryptIndex;
343 for ($k = 0; $k < strlen($text); $k++) {
345 $j = ($j + $keyStream[$i]) & 255;
346 $temp = $keyStream[$i];
347 $keyStream[$i] = $keyStream[$j];
348 $keyStream[$j] = $temp;
349 $temp = $keyStream[($keyStream[$i] + $keyStream[$j]) & 255];
350 $newText.= chr(ord($text[$k]) ^ $temp);
353 if ($this->continuousBuffer) {
355 case CRYPT_RC4_ENCRYPT:
356 $this->encryptStream = $keyStream;
357 $this->encryptIndex = array($i, $j);
359 case CRYPT_RC4_DECRYPT:
360 $this->decryptStream = $keyStream;
361 $this->decryptIndex = array($i, $j);
369 * Treat consecutive "packets" as if they are a continuous buffer.
371 * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
372 * will yield different outputs:
375 * echo $rc4->encrypt(substr($plaintext, 0, 8));
376 * echo $rc4->encrypt(substr($plaintext, 8, 8));
379 * echo $rc4->encrypt($plaintext);
382 * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
383 * another, as demonstrated with the following:
386 * $rc4->encrypt(substr($plaintext, 0, 8));
387 * echo $rc4->decrypt($des->encrypt(substr($plaintext, 8, 8)));
390 * echo $rc4->decrypt($des->encrypt(substr($plaintext, 8, 8)));
393 * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
394 * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
395 * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
397 * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
398 * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
399 * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
400 * however, they are also less intuitive and more likely to cause you problems.
402 * @see Crypt_RC4::disableContinuousBuffer()
405 function enableContinuousBuffer()
407 $this->continuousBuffer = true;
411 * Treat consecutive packets as if they are a discontinuous buffer.
413 * The default behavior.
415 * @see Crypt_RC4::enableContinuousBuffer()
418 function disableContinuousBuffer()
420 if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_INTERNAL ) {
421 $this->encryptIndex = $this->decryptIndex = array(0, 0);
422 $this->setKey($this->key);
425 $this->continuousBuffer = false;
431 * Since RC4 is a stream cipher and not a block cipher, no padding is necessary. The only reason this function is
432 * included is so that you can switch between a block cipher and a stream cipher transparently.
434 * @see Crypt_RC4::disablePadding()
437 function enablePadding()
444 * @see Crypt_RC4::enablePadding()
447 function disablePadding()
454 * Will be called, automatically, if you're using PHP5. If you're using PHP4, call it yourself. Only really
455 * needs to be called if mcrypt is being used.
459 function __destruct()
461 if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
462 $this->_closeMCrypt();
467 * Properly close the MCrypt objects.
471 function _closeMCrypt()
473 if ( $this->encryptStream !== false ) {
474 if ( $this->continuousBuffer ) {
475 mcrypt_generic_deinit($this->encryptStream);
478 mcrypt_module_close($this->encryptStream);
480 $this->encryptStream = false;
483 if ( $this->decryptStream !== false ) {
484 if ( $this->continuousBuffer ) {
485 mcrypt_generic_deinit($this->decryptStream);
488 mcrypt_module_close($this->decryptStream);
490 $this->decryptStream = false;