]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/extlib/Crypt/RC4.php
Merge remote branch 'statusnet/testing' into crypt-rsa-switch
[quix0rs-gnu-social.git] / plugins / OStatus / extlib / Crypt / RC4.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
4 /**
5  * Pure-PHP implementation of RC4.
6  *
7  * Uses mcrypt, if available, and an internal implementation, otherwise.
8  *
9  * PHP versions 4 and 5
10  *
11  * Useful resources are as follows:
12  *
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}
15  *
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.
18  *
19  * Here's a short example of how to use this library:
20  * <code>
21  * <?php
22  *    include('Crypt/RC4.php');
23  *
24  *    $rc4 = new Crypt_RC4();
25  *
26  *    $rc4->setKey('abcdefgh');
27  *
28  *    $size = 10 * 1024;
29  *    $plaintext = '';
30  *    for ($i = 0; $i < $size; $i++) {
31  *        $plaintext.= 'a';
32  *    }
33  *
34  *    echo $rc4->decrypt($rc4->encrypt($plaintext));
35  * ?>
36  * </code>
37  *
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.
42  *
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.
47  *
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,
51  * MA  02111-1307  USA
52  *
53  * @category   Crypt
54  * @package    Crypt_RC4
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
60  */
61
62 /**#@+
63  * @access private
64  * @see Crypt_RC4::Crypt_RC4()
65  */
66 /**
67  * Toggles the internal implementation
68  */
69 define('CRYPT_RC4_MODE_INTERNAL', 1);
70 /**
71  * Toggles the mcrypt implementation
72  */
73 define('CRYPT_RC4_MODE_MCRYPT', 2);
74 /**#@-*/
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 /**
85  * Pure-PHP implementation of RC4.
86  *
87  * @author  Jim Wigginton <terrafrost@php.net>
88  * @version 0.1.0
89  * @access  public
90  * @package Crypt_RC4
91  */
92 class Crypt_RC4 {
93     /**
94      * The Key
95      *
96      * @see Crypt_RC4::setKey()
97      * @var String
98      * @access private
99      */
100     var $key = "\0";
101
102     /**
103      * The Key Stream for encryption
104      *
105      * If CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT, this will be equal to the mcrypt object
106      *
107      * @see Crypt_RC4::setKey()
108      * @var Array
109      * @access private
110      */
111     var $encryptStream = false;
112
113     /**
114      * The Key Stream for decryption
115      *
116      * If CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT, this will be equal to the mcrypt object
117      *
118      * @see Crypt_RC4::setKey()
119      * @var Array
120      * @access private
121      */
122     var $decryptStream = false;
123
124     /**
125      * The $i and $j indexes for encryption
126      *
127      * @see Crypt_RC4::_crypt()
128      * @var Integer
129      * @access private
130      */
131     var $encryptIndex = 0;
132
133     /**
134      * The $i and $j indexes for decryption
135      *
136      * @see Crypt_RC4::_crypt()
137      * @var Integer
138      * @access private
139      */
140     var $decryptIndex = 0;
141
142     /**
143      * MCrypt parameters
144      *
145      * @see Crypt_RC4::setMCrypt()
146      * @var Array
147      * @access private
148      */
149     var $mcrypt = array('', '');
150
151     /**
152      * The Encryption Algorithm
153      *
154      * Only used if CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT.  Only possible values are MCRYPT_RC4 or MCRYPT_ARCFOUR.
155      *
156      * @see Crypt_RC4::Crypt_RC4()
157      * @var Integer
158      * @access private
159      */
160     var $mode;
161
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
186         switch ( CRYPT_RC4_MODE ) {
187             case CRYPT_RC4_MODE_MCRYPT:
188                 switch (true) {
189                     case defined('MCRYPT_ARCFOUR'):
190                         $this->mode = MCRYPT_ARCFOUR;
191                         break;
192                     case defined('MCRYPT_RC4');
193                         $this->mode = MCRYPT_RC4;
194                 }
195         }
196     }
197
198     /**
199      * Sets the key.
200      *
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.
203      *
204      * @access public
205      * @param String $key
206      */
207     function setKey($key)
208     {
209         $this->key = $key;
210
211         if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
212             return;
213         }
214
215         $keyLength = strlen($key);
216         $keyStream = array();
217         for ($i = 0; $i < 256; $i++) {
218             $keyStream[$i] = $i;
219         }
220         $j = 0;
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;
226         }
227
228         $this->encryptIndex = $this->decryptIndex = array(0, 0);
229         $this->encryptStream = $this->decryptStream = $keyStream;
230     }
231
232     /**
233      * Dummy function.
234      *
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
237      * calling setKey().
238      *
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:
243      *
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}
246      *
247      * @param String $iv
248      * @see Crypt_RC4::setKey()
249      * @access public
250      */
251     function setIV($iv)
252     {
253     }
254
255     /**
256      * Sets MCrypt parameters. (optional)
257      *
258      * If MCrypt is being used, empty strings will be used, unless otherwise specified.
259      *
260      * @link http://php.net/function.mcrypt-module-open#function.mcrypt-module-open
261      * @access public
262      * @param optional Integer $algorithm_directory
263      * @param optional Integer $mode_directory
264      */
265     function setMCrypt($algorithm_directory = '', $mode_directory = '')
266     {
267         if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
268             $this->mcrypt = array($algorithm_directory, $mode_directory);
269             $this->_closeMCrypt();
270         }
271     }
272
273     /**
274      * Encrypts a message.
275      *
276      * @see Crypt_RC4::_crypt()
277      * @access public
278      * @param String $plaintext
279      */
280     function encrypt($plaintext)
281     {
282         return $this->_crypt($plaintext, CRYPT_RC4_ENCRYPT);
283     }
284
285     /**
286      * Decrypts a message.
287      *
288      * $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)).
289      * Atleast if the continuous buffer is disabled.
290      *
291      * @see Crypt_RC4::_crypt()
292      * @access public
293      * @param String $ciphertext
294      */
295     function decrypt($ciphertext)
296     {
297         return $this->_crypt($ciphertext, CRYPT_RC4_DECRYPT);
298     }
299
300     /**
301      * Encrypts or decrypts a message.
302      *
303      * @see Crypt_RC4::encrypt()
304      * @see Crypt_RC4::decrypt()
305      * @access private
306      * @param String $text
307      * @param Integer $mode
308      */
309     function _crypt($text, $mode)
310     {
311         if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
312             $keyStream = $mode == CRYPT_RC4_ENCRYPT ? 'encryptStream' : 'decryptStream';
313
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, '');
319             }
320             $newText = mcrypt_generic($this->$keyStream, $text);
321             if (!$this->continuousBuffer) {
322                 mcrypt_generic_deinit($this->$keyStream);
323             }
324
325             return $newText;
326         }
327
328         if ($this->encryptStream === false) {
329             $this->setKey($this->key);
330         }
331
332         switch ($mode) {
333             case CRYPT_RC4_ENCRYPT:
334                 $keyStream = $this->encryptStream;
335                 list($i, $j) = $this->encryptIndex;
336                 break;
337             case CRYPT_RC4_DECRYPT:
338                 $keyStream = $this->decryptStream;
339                 list($i, $j) = $this->decryptIndex;
340         }
341
342         $newText = '';
343         for ($k = 0; $k < strlen($text); $k++) {
344             $i = ($i + 1) & 255;
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);
351         }
352
353         if ($this->continuousBuffer) {
354             switch ($mode) {
355                 case CRYPT_RC4_ENCRYPT:
356                     $this->encryptStream = $keyStream;
357                     $this->encryptIndex = array($i, $j);
358                     break;
359                 case CRYPT_RC4_DECRYPT:
360                     $this->decryptStream = $keyStream;
361                     $this->decryptIndex = array($i, $j);
362             }
363         }
364
365         return $newText;
366     }
367
368     /**
369      * Treat consecutive "packets" as if they are a continuous buffer.
370      *
371      * Say you have a 16-byte plaintext $plaintext.  Using the default behavior, the two following code snippets
372      * will yield different outputs:
373      *
374      * <code>
375      *    echo $rc4->encrypt(substr($plaintext, 0, 8));
376      *    echo $rc4->encrypt(substr($plaintext, 8, 8));
377      * </code>
378      * <code>
379      *    echo $rc4->encrypt($plaintext);
380      * </code>
381      *
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:
384      *
385      * <code>
386      *    $rc4->encrypt(substr($plaintext, 0, 8));
387      *    echo $rc4->decrypt($des->encrypt(substr($plaintext, 8, 8)));
388      * </code>
389      * <code>
390      *    echo $rc4->decrypt($des->encrypt(substr($plaintext, 8, 8)));
391      * </code>
392      *
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.
396      *
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.
401      *
402      * @see Crypt_RC4::disableContinuousBuffer()
403      * @access public
404      */
405     function enableContinuousBuffer()
406     {
407         $this->continuousBuffer = true;
408     }
409
410     /**
411      * Treat consecutive packets as if they are a discontinuous buffer.
412      *
413      * The default behavior.
414      *
415      * @see Crypt_RC4::enableContinuousBuffer()
416      * @access public
417      */
418     function disableContinuousBuffer()
419     {
420         if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_INTERNAL ) {
421             $this->encryptIndex = $this->decryptIndex = array(0, 0);
422             $this->setKey($this->key);
423         }
424
425         $this->continuousBuffer = false;
426     }
427
428     /**
429      * Dummy function.
430      *
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.
433      *
434      * @see Crypt_RC4::disablePadding()
435      * @access public
436      */
437     function enablePadding()
438     {
439     }
440
441     /**
442      * Dummy function.
443      *
444      * @see Crypt_RC4::enablePadding()
445      * @access public
446      */
447     function disablePadding()
448     {
449     }
450
451     /**
452      * Class destructor.
453      *
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.
456      *
457      * @access public
458      */
459     function __destruct()
460     {
461         if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
462             $this->_closeMCrypt();
463         }
464     }
465
466     /**
467      * Properly close the MCrypt objects.
468      *
469      * @access prviate
470      */
471     function _closeMCrypt()
472     {
473         if ( $this->encryptStream !== false ) {
474             if ( $this->continuousBuffer ) {
475                 mcrypt_generic_deinit($this->encryptStream);
476             }
477
478             mcrypt_module_close($this->encryptStream);
479
480             $this->encryptStream = false;
481         }
482
483         if ( $this->decryptStream !== false ) {
484             if ( $this->continuousBuffer ) {
485                 mcrypt_generic_deinit($this->decryptStream);
486             }
487
488             mcrypt_module_close($this->decryptStream);
489
490             $this->decryptStream = false;
491         }
492     }
493 }