]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/extlib/Crypt/AES.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into testing
[quix0rs-gnu-social.git] / plugins / OStatus / extlib / Crypt / AES.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
4 /**
5  * Pure-PHP implementation of AES.
6  *
7  * Uses mcrypt, if available, and an internal implementation, otherwise.
8  *
9  * PHP versions 4 and 5
10  *
11  * If {@link Crypt_AES::setKeyLength() setKeyLength()} isn't called, it'll be calculated from
12  * {@link Crypt_AES::setKey() setKey()}.  ie. if the key is 128-bits, the key length will be 128-bits.  If it's 136-bits
13  * it'll be null-padded to 160-bits and 160 bits will be the key length until {@link Crypt_Rijndael::setKey() setKey()}
14  * is called, again, at which point, it'll be recalculated.
15  *
16  * Since Crypt_AES extends Crypt_Rijndael, some functions are available to be called that, in the context of AES, don't
17  * make a whole lot of sense.  {@link Crypt_AES::setBlockLength() setBlockLength()}, for instance.  Calling that function,
18  * however possible, won't do anything (AES has a fixed block length whereas Rijndael has a variable one).
19  *
20  * Here's a short example of how to use this library:
21  * <code>
22  * <?php
23  *    include('Crypt/AES.php');
24  *
25  *    $aes = new Crypt_AES();
26  *
27  *    $aes->setKey('abcdefghijklmnop');
28  *
29  *    $size = 10 * 1024;
30  *    $plaintext = '';
31  *    for ($i = 0; $i < $size; $i++) {
32  *        $plaintext.= 'a';
33  *    }
34  *
35  *    echo $aes->decrypt($aes->encrypt($plaintext));
36  * ?>
37  * </code>
38  *
39  * LICENSE: This library is free software; you can redistribute it and/or
40  * modify it under the terms of the GNU Lesser General Public
41  * License as published by the Free Software Foundation; either
42  * version 2.1 of the License, or (at your option) any later version.
43  *
44  * This library is distributed in the hope that it will be useful,
45  * but WITHOUT ANY WARRANTY; without even the implied warranty of
46  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
47  * Lesser General Public License for more details.
48  *
49  * You should have received a copy of the GNU Lesser General Public
50  * License along with this library; if not, write to the Free Software
51  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
52  * MA  02111-1307  USA
53  *
54  * @category   Crypt
55  * @package    Crypt_AES
56  * @author     Jim Wigginton <terrafrost@php.net>
57  * @copyright  MMVIII Jim Wigginton
58  * @license    http://www.gnu.org/licenses/lgpl.txt
59  * @version    $Id: AES.php,v 1.7 2010/02/09 06:10:25 terrafrost Exp $
60  * @link       http://phpseclib.sourceforge.net
61  */
62
63 /**
64  * Include Crypt_Rijndael
65  */
66 require_once 'Rijndael.php';
67
68 /**#@+
69  * @access public
70  * @see Crypt_AES::encrypt()
71  * @see Crypt_AES::decrypt()
72  */
73 /**
74  * Encrypt / decrypt using the Counter mode.
75  *
76  * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
77  *
78  * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
79  */
80 define('CRYPT_AES_MODE_CTR', -1);
81 /**
82  * Encrypt / decrypt using the Electronic Code Book mode.
83  *
84  * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
85  */
86 define('CRYPT_AES_MODE_ECB', 1);
87 /**
88  * Encrypt / decrypt using the Code Book Chaining mode.
89  *
90  * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
91  */
92 define('CRYPT_AES_MODE_CBC', 2);
93 /**#@-*/
94
95 /**#@+
96  * @access private
97  * @see Crypt_AES::Crypt_AES()
98  */
99 /**
100  * Toggles the internal implementation
101  */
102 define('CRYPT_AES_MODE_INTERNAL', 1);
103 /**
104  * Toggles the mcrypt implementation
105  */
106 define('CRYPT_AES_MODE_MCRYPT', 2);
107 /**#@-*/
108
109 /**
110  * Pure-PHP implementation of AES.
111  *
112  * @author  Jim Wigginton <terrafrost@php.net>
113  * @version 0.1.0
114  * @access  public
115  * @package Crypt_AES
116  */
117 class Crypt_AES extends Crypt_Rijndael {
118     /**
119      * mcrypt resource for encryption
120      *
121      * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
122      * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
123      *
124      * @see Crypt_AES::encrypt()
125      * @var String
126      * @access private
127      */
128     var $enmcrypt;
129
130     /**
131      * mcrypt resource for decryption
132      *
133      * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
134      * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
135      *
136      * @see Crypt_AES::decrypt()
137      * @var String
138      * @access private
139      */
140     var $demcrypt;
141
142     /**
143      * Default Constructor.
144      *
145      * Determines whether or not the mcrypt extension should be used.  $mode should only, at present, be
146      * CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC.  If not explictly set, CRYPT_AES_MODE_CBC will be used.
147      *
148      * @param optional Integer $mode
149      * @return Crypt_AES
150      * @access public
151      */
152     function Crypt_AES($mode = CRYPT_AES_MODE_CBC)
153     {
154         if ( !defined('CRYPT_AES_MODE') ) {
155             switch (true) {
156                 case extension_loaded('mcrypt'):
157                     // i'd check to see if aes was supported, by doing in_array('des', mcrypt_list_algorithms('')),
158                     // but since that can be changed after the object has been created, there doesn't seem to be
159                     // a lot of point...
160                     define('CRYPT_AES_MODE', CRYPT_AES_MODE_MCRYPT);
161                     break;
162                 default:
163                     define('CRYPT_AES_MODE', CRYPT_AES_MODE_INTERNAL);
164             }
165         }
166
167         switch ( CRYPT_AES_MODE ) {
168             case CRYPT_AES_MODE_MCRYPT:
169                 switch ($mode) {
170                     case CRYPT_AES_MODE_ECB:
171                         $this->mode = MCRYPT_MODE_ECB;
172                         break;
173                     case CRYPT_AES_MODE_CTR:
174                         // ctr doesn't have a constant associated with it even though it appears to be fairly widely
175                         // supported.  in lieu of knowing just how widely supported it is, i've, for now, opted not to
176                         // include a compatibility layer.  the layer has been implemented but, for now, is commented out.
177                         $this->mode = 'ctr';
178                         //$this->mode = in_array('ctr', mcrypt_list_modes()) ? 'ctr' : CRYPT_AES_MODE_CTR;
179                         break;
180                     case CRYPT_AES_MODE_CBC:
181                     default:
182                         $this->mode = MCRYPT_MODE_CBC;
183                 }
184
185                 break;
186             default:
187                 switch ($mode) {
188                     case CRYPT_AES_MODE_ECB:
189                         $this->mode = CRYPT_RIJNDAEL_MODE_ECB;
190                         break;
191                     case CRYPT_AES_MODE_CTR:
192                         $this->mode = CRYPT_RIJNDAEL_MODE_CTR;
193                         break;
194                     case CRYPT_AES_MODE_CBC:
195                     default:
196                         $this->mode = CRYPT_RIJNDAEL_MODE_CBC;
197                 }
198         }
199
200         if (CRYPT_AES_MODE == CRYPT_AES_MODE_INTERNAL) {
201             parent::Crypt_Rijndael($this->mode);
202         }
203     }
204
205     /**
206      * Dummy function
207      *
208      * Since Crypt_AES extends Crypt_Rijndael, this function is, technically, available, but it doesn't do anything.
209      *
210      * @access public
211      * @param Integer $length
212      */
213     function setBlockLength($length)
214     {
215         return;
216     }
217
218     /**
219      * Encrypts a message.
220      *
221      * $plaintext will be padded with up to 16 additional bytes.  Other AES implementations may or may not pad in the
222      * same manner.  Other common approaches to padding and the reasons why it's necessary are discussed in the following
223      * URL:
224      *
225      * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
226      *
227      * An alternative to padding is to, separately, send the length of the file.  This is what SSH, in fact, does.
228      * strlen($plaintext) will still need to be a multiple of 16, however, arbitrary values can be added to make it that
229      * length.
230      *
231      * @see Crypt_AES::decrypt()
232      * @access public
233      * @param String $plaintext
234      */
235     function encrypt($plaintext)
236     {
237         if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
238             $this->_mcryptSetup();
239             /*
240             if ($this->mode == CRYPT_AES_MODE_CTR) {
241                 $iv = $this->encryptIV;
242                 $xor = mcrypt_generic($this->enmcrypt, $this->_generate_xor(strlen($plaintext), $iv));
243                 $ciphertext = $plaintext ^ $xor;
244                 if ($this->continuousBuffer) {
245                     $this->encryptIV = $iv;
246                 }
247                 return $ciphertext;
248             }
249             */
250
251             if ($this->mode != 'ctr') {
252                 $plaintext = $this->_pad($plaintext);
253             }
254
255             $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
256
257             if (!$this->continuousBuffer) {
258                 mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
259             }
260
261             return $ciphertext;
262         }
263
264         return parent::encrypt($plaintext);
265     }
266
267     /**
268      * Decrypts a message.
269      *
270      * If strlen($ciphertext) is not a multiple of 16, null bytes will be added to the end of the string until it is.
271      *
272      * @see Crypt_AES::encrypt()
273      * @access public
274      * @param String $ciphertext
275      */
276     function decrypt($ciphertext)
277     {
278         if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
279             $this->_mcryptSetup();
280             /*
281             if ($this->mode == CRYPT_AES_MODE_CTR) {
282                 $iv = $this->decryptIV;
283                 $xor = mcrypt_generic($this->enmcrypt, $this->_generate_xor(strlen($ciphertext), $iv));
284                 $plaintext = $ciphertext ^ $xor;
285                 if ($this->continuousBuffer) {
286                     $this->decryptIV = $iv;
287                 }
288                 return $plaintext;
289             }
290             */
291
292             if ($this->mode != 'ctr') {
293                 // we pad with chr(0) since that's what mcrypt_generic does.  to quote from http://php.net/function.mcrypt-generic :
294                 // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
295                 $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 15) & 0xFFFFFFF0, chr(0));
296             }
297
298             $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
299
300             if (!$this->continuousBuffer) {
301                 mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
302             }
303
304             return $this->mode != 'ctr' ? $this->_unpad($plaintext) : $plaintext;
305         }
306
307         return parent::decrypt($ciphertext);
308     }
309
310     /**
311      * Setup mcrypt
312      *
313      * Validates all the variables.
314      *
315      * @access private
316      */
317     function _mcryptSetup()
318     {
319         if (!$this->changed) {
320             return;
321         }
322
323         if (!$this->explicit_key_length) {
324             // this just copied from Crypt_Rijndael::_setup()
325             $length = strlen($this->key) >> 2;
326             if ($length > 8) {
327                 $length = 8;
328             } else if ($length < 4) {
329                 $length = 4;
330             }
331             $this->Nk = $length;
332             $this->key_size = $length << 2;
333         }
334
335         switch ($this->Nk) {
336             case 4: // 128
337                 $this->key_size = 16;
338                 break;
339             case 5: // 160
340             case 6: // 192
341                 $this->key_size = 24;
342                 break;
343             case 7: // 224
344             case 8: // 256
345                 $this->key_size = 32;
346         }
347
348         $this->key = substr($this->key, 0, $this->key_size);
349         $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($this->iv, 0, 16), 16, chr(0));
350
351         if (!isset($this->enmcrypt)) {
352             $mode = $this->mode;
353             //$mode = $this->mode == CRYPT_AES_MODE_CTR ? MCRYPT_MODE_ECB : $this->mode;
354
355             $this->demcrypt = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mode, '');
356             $this->enmcrypt = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', $mode, '');
357         } // else should mcrypt_generic_deinit be called?
358
359         mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
360         mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
361
362         $this->changed = false;
363     }
364
365     /**
366      * Encrypts a block
367      *
368      * Optimized over Crypt_Rijndael's implementation by means of loop unrolling.
369      *
370      * @see Crypt_Rijndael::_encryptBlock()
371      * @access private
372      * @param String $in
373      * @return String
374      */
375     function _encryptBlock($in)
376     {
377         $state = unpack('N*word', $in);
378
379         $Nr = $this->Nr;
380         $w = $this->w;
381         $t0 = $this->t0;
382         $t1 = $this->t1;
383         $t2 = $this->t2;
384         $t3 = $this->t3;
385
386         // addRoundKey and reindex $state
387         $state = array(
388             $state['word1'] ^ $w[0][0],
389             $state['word2'] ^ $w[0][1],
390             $state['word3'] ^ $w[0][2],
391             $state['word4'] ^ $w[0][3]
392         );
393
394         // shiftRows + subWord + mixColumns + addRoundKey
395         // we could loop unroll this and use if statements to do more rounds as necessary, but, in my tests, that yields
396         // only a marginal improvement.  since that also, imho, hinders the readability of the code, i've opted not to do it.
397         for ($round = 1; $round < $this->Nr; $round++) {
398             $state = array(
399                 $t0[$state[0] & 0xFF000000] ^ $t1[$state[1] & 0x00FF0000] ^ $t2[$state[2] & 0x0000FF00] ^ $t3[$state[3] & 0x000000FF] ^ $w[$round][0],
400                 $t0[$state[1] & 0xFF000000] ^ $t1[$state[2] & 0x00FF0000] ^ $t2[$state[3] & 0x0000FF00] ^ $t3[$state[0] & 0x000000FF] ^ $w[$round][1],
401                 $t0[$state[2] & 0xFF000000] ^ $t1[$state[3] & 0x00FF0000] ^ $t2[$state[0] & 0x0000FF00] ^ $t3[$state[1] & 0x000000FF] ^ $w[$round][2],
402                 $t0[$state[3] & 0xFF000000] ^ $t1[$state[0] & 0x00FF0000] ^ $t2[$state[1] & 0x0000FF00] ^ $t3[$state[2] & 0x000000FF] ^ $w[$round][3]
403             );
404
405         }
406
407         // subWord
408         $state = array(
409             $this->_subWord($state[0]),
410             $this->_subWord($state[1]),
411             $this->_subWord($state[2]),
412             $this->_subWord($state[3])
413         );
414
415         // shiftRows + addRoundKey
416         $state = array(
417             ($state[0] & 0xFF000000) ^ ($state[1] & 0x00FF0000) ^ ($state[2] & 0x0000FF00) ^ ($state[3] & 0x000000FF) ^ $this->w[$this->Nr][0],
418             ($state[1] & 0xFF000000) ^ ($state[2] & 0x00FF0000) ^ ($state[3] & 0x0000FF00) ^ ($state[0] & 0x000000FF) ^ $this->w[$this->Nr][1],
419             ($state[2] & 0xFF000000) ^ ($state[3] & 0x00FF0000) ^ ($state[0] & 0x0000FF00) ^ ($state[1] & 0x000000FF) ^ $this->w[$this->Nr][2],
420             ($state[3] & 0xFF000000) ^ ($state[0] & 0x00FF0000) ^ ($state[1] & 0x0000FF00) ^ ($state[2] & 0x000000FF) ^ $this->w[$this->Nr][3]
421         );
422
423         return pack('N*', $state[0], $state[1], $state[2], $state[3]);
424     }
425
426     /**
427      * Decrypts a block
428      *
429      * Optimized over Crypt_Rijndael's implementation by means of loop unrolling.
430      *
431      * @see Crypt_Rijndael::_decryptBlock()
432      * @access private
433      * @param String $in
434      * @return String
435      */
436     function _decryptBlock($in)
437     {
438         $state = unpack('N*word', $in);
439
440         $Nr = $this->Nr;
441         $dw = $this->dw;
442         $dt0 = $this->dt0;
443         $dt1 = $this->dt1;
444         $dt2 = $this->dt2;
445         $dt3 = $this->dt3;
446
447         // addRoundKey and reindex $state
448         $state = array(
449             $state['word1'] ^ $dw[$this->Nr][0],
450             $state['word2'] ^ $dw[$this->Nr][1],
451             $state['word3'] ^ $dw[$this->Nr][2],
452             $state['word4'] ^ $dw[$this->Nr][3]
453         );
454
455
456         // invShiftRows + invSubBytes + invMixColumns + addRoundKey
457         for ($round = $this->Nr - 1; $round > 0; $round--) {
458             $state = array(
459                 $dt0[$state[0] & 0xFF000000] ^ $dt1[$state[3] & 0x00FF0000] ^ $dt2[$state[2] & 0x0000FF00] ^ $dt3[$state[1] & 0x000000FF] ^ $dw[$round][0],
460                 $dt0[$state[1] & 0xFF000000] ^ $dt1[$state[0] & 0x00FF0000] ^ $dt2[$state[3] & 0x0000FF00] ^ $dt3[$state[2] & 0x000000FF] ^ $dw[$round][1],
461                 $dt0[$state[2] & 0xFF000000] ^ $dt1[$state[1] & 0x00FF0000] ^ $dt2[$state[0] & 0x0000FF00] ^ $dt3[$state[3] & 0x000000FF] ^ $dw[$round][2],
462                 $dt0[$state[3] & 0xFF000000] ^ $dt1[$state[2] & 0x00FF0000] ^ $dt2[$state[1] & 0x0000FF00] ^ $dt3[$state[0] & 0x000000FF] ^ $dw[$round][3]
463             );
464         }
465
466         // invShiftRows + invSubWord + addRoundKey
467         $state = array(
468             $this->_invSubWord(($state[0] & 0xFF000000) ^ ($state[3] & 0x00FF0000) ^ ($state[2] & 0x0000FF00) ^ ($state[1] & 0x000000FF)) ^ $dw[0][0],
469             $this->_invSubWord(($state[1] & 0xFF000000) ^ ($state[0] & 0x00FF0000) ^ ($state[3] & 0x0000FF00) ^ ($state[2] & 0x000000FF)) ^ $dw[0][1],
470             $this->_invSubWord(($state[2] & 0xFF000000) ^ ($state[1] & 0x00FF0000) ^ ($state[0] & 0x0000FF00) ^ ($state[3] & 0x000000FF)) ^ $dw[0][2],
471             $this->_invSubWord(($state[3] & 0xFF000000) ^ ($state[2] & 0x00FF0000) ^ ($state[1] & 0x0000FF00) ^ ($state[0] & 0x000000FF)) ^ $dw[0][3]
472         );
473
474         return pack('N*', $state[0], $state[1], $state[2], $state[3]);
475     }
476 }
477
478 // vim: ts=4:sw=4:et:
479 // vim6: fdl=1: