2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
5 * Pure-PHP implementation of AES.
7 * Uses mcrypt, if available, and an internal implementation, otherwise.
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.
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).
20 * Here's a short example of how to use this library:
23 * include('Crypt/AES.php');
25 * $aes = new Crypt_AES();
27 * $aes->setKey('abcdefghijklmnop');
31 * for ($i = 0; $i < $size; $i++) {
35 * echo $aes->decrypt($aes->encrypt($plaintext));
39 * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
40 * of this software and associated documentation files (the "Software"), to deal
41 * in the Software without restriction, including without limitation the rights
42 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
43 * copies of the Software, and to permit persons to whom the Software is
44 * furnished to do so, subject to the following conditions:
46 * The above copyright notice and this permission notice shall be included in
47 * all copies or substantial portions of the Software.
49 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
50 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
51 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
52 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
53 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
54 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
59 * @author Jim Wigginton <terrafrost@php.net>
60 * @copyright MMVIII Jim Wigginton
61 * @license http://www.opensource.org/licenses/mit-license.html MIT License
62 * @version $Id: AES.php,v 1.7 2010/02/09 06:10:25 terrafrost Exp $
63 * @link http://phpseclib.sourceforge.net
67 * Include Crypt_Rijndael
69 if (!class_exists('Crypt_Rijndael')) {
70 require_once 'Rijndael.php';
75 * @see Crypt_AES::encrypt()
76 * @see Crypt_AES::decrypt()
79 * Encrypt / decrypt using the Counter mode.
81 * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
83 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
85 define('CRYPT_AES_MODE_CTR', -1);
87 * Encrypt / decrypt using the Electronic Code Book mode.
89 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
91 define('CRYPT_AES_MODE_ECB', 1);
93 * Encrypt / decrypt using the Code Book Chaining mode.
95 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
97 define('CRYPT_AES_MODE_CBC', 2);
99 * Encrypt / decrypt using the Cipher Feedback mode.
101 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
103 define('CRYPT_AES_MODE_CFB', 3);
105 * Encrypt / decrypt using the Cipher Feedback mode.
107 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
109 define('CRYPT_AES_MODE_OFB', 4);
114 * @see Crypt_AES::Crypt_AES()
117 * Toggles the internal implementation
119 define('CRYPT_AES_MODE_INTERNAL', 1);
121 * Toggles the mcrypt implementation
123 define('CRYPT_AES_MODE_MCRYPT', 2);
127 * Pure-PHP implementation of AES.
129 * @author Jim Wigginton <terrafrost@php.net>
134 class Crypt_AES
extends Crypt_Rijndael
{
136 * mcrypt resource for encryption
138 * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
139 * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
141 * @see Crypt_AES::encrypt()
148 * mcrypt resource for decryption
150 * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
151 * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
153 * @see Crypt_AES::decrypt()
160 * mcrypt resource for CFB mode
162 * @see Crypt_AES::encrypt()
163 * @see Crypt_AES::decrypt()
170 * Default Constructor.
172 * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be
173 * CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC. If not explictly set, CRYPT_AES_MODE_CBC will be used.
175 * @param optional Integer $mode
179 function Crypt_AES($mode = CRYPT_AES_MODE_CBC
)
181 if ( !defined('CRYPT_AES_MODE') ) {
183 case extension_loaded('mcrypt') && in_array('rijndael-128', mcrypt_list_algorithms()):
184 define('CRYPT_AES_MODE', CRYPT_AES_MODE_MCRYPT
);
187 define('CRYPT_AES_MODE', CRYPT_AES_MODE_INTERNAL
);
191 switch ( CRYPT_AES_MODE
) {
192 case CRYPT_AES_MODE_MCRYPT
:
194 case CRYPT_AES_MODE_ECB
:
195 $this->paddable
= true;
196 $this->mode
= MCRYPT_MODE_ECB
;
198 case CRYPT_AES_MODE_CTR
:
199 // ctr doesn't have a constant associated with it even though it appears to be fairly widely
200 // supported. in lieu of knowing just how widely supported it is, i've, for now, opted not to
201 // include a compatibility layer. the layer has been implemented but, for now, is commented out.
203 //$this->mode = in_array('ctr', mcrypt_list_modes()) ? 'ctr' : CRYPT_AES_MODE_CTR;
205 case CRYPT_AES_MODE_CFB
:
206 $this->mode
= 'ncfb';
208 case CRYPT_AES_MODE_OFB
:
209 $this->mode
= MCRYPT_MODE_NOFB
;
211 case CRYPT_AES_MODE_CBC
:
213 $this->paddable
= true;
214 $this->mode
= MCRYPT_MODE_CBC
;
217 $this->debuffer
= $this->enbuffer
= '';
222 case CRYPT_AES_MODE_ECB
:
223 $this->paddable
= true;
224 $this->mode
= CRYPT_RIJNDAEL_MODE_ECB
;
226 case CRYPT_AES_MODE_CTR
:
227 $this->mode
= CRYPT_RIJNDAEL_MODE_CTR
;
229 case CRYPT_AES_MODE_CFB
:
230 $this->mode
= CRYPT_RIJNDAEL_MODE_CFB
;
232 case CRYPT_AES_MODE_OFB
:
233 $this->mode
= CRYPT_RIJNDAEL_MODE_OFB
;
235 case CRYPT_AES_MODE_CBC
:
237 $this->paddable
= true;
238 $this->mode
= CRYPT_RIJNDAEL_MODE_CBC
;
242 if (CRYPT_AES_MODE
== CRYPT_AES_MODE_INTERNAL
) {
243 parent
::Crypt_Rijndael($this->mode
);
250 * Since Crypt_AES extends Crypt_Rijndael, this function is, technically, available, but it doesn't do anything.
253 * @param Integer $length
255 function setBlockLength($length)
262 * Sets the initialization vector. (optional)
264 * SetIV is not required when CRYPT_RIJNDAEL_MODE_ECB is being used. If not explictly set, it'll be assumed
273 if ( CRYPT_AES_MODE
== CRYPT_AES_MODE_MCRYPT
) {
274 $this->changed
= true;
279 * Encrypts a message.
281 * $plaintext will be padded with up to 16 additional bytes. Other AES implementations may or may not pad in the
282 * same manner. Other common approaches to padding and the reasons why it's necessary are discussed in the following
285 * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
287 * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
288 * strlen($plaintext) will still need to be a multiple of 16, however, arbitrary values can be added to make it that
291 * @see Crypt_AES::decrypt()
293 * @param String $plaintext
295 function encrypt($plaintext)
297 if ( CRYPT_AES_MODE
== CRYPT_AES_MODE_MCRYPT
) {
298 $changed = $this->changed
;
299 $this->_mcryptSetup();
301 if ($this->mode == CRYPT_AES_MODE_CTR) {
302 $iv = $this->encryptIV;
303 $xor = mcrypt_generic($this->enmcrypt, $this->_generate_xor(strlen($plaintext), $iv));
304 $ciphertext = $plaintext ^ $xor;
305 if ($this->continuousBuffer) {
306 $this->encryptIV = $iv;
311 // re: http://phpseclib.sourceforge.net/cfb-demo.phps
312 // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
313 // rewritten CFB implementation the above outputs the same thing twice.
314 if ($this->mode
== 'ncfb') {
316 $this->ecb
= mcrypt_module_open(MCRYPT_RIJNDAEL_128
, '', MCRYPT_MODE_ECB
, '');
317 mcrypt_generic_init($this->ecb
, $this->key
, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
320 if (strlen($this->enbuffer
)) {
321 $ciphertext = $plaintext ^
substr($this->encryptIV
, strlen($this->enbuffer
));
322 $this->enbuffer
.= $ciphertext;
323 if (strlen($this->enbuffer
) == 16) {
324 $this->encryptIV
= $this->enbuffer
;
325 $this->enbuffer
= '';
326 mcrypt_generic_init($this->enmcrypt
, $this->key
, $this->encryptIV
);
328 $plaintext = substr($plaintext, strlen($ciphertext));
333 $last_pos = strlen($plaintext) & 0xFFFFFFF0;
334 $ciphertext.= $last_pos ?
mcrypt_generic($this->enmcrypt
, substr($plaintext, 0, $last_pos)) : '';
336 if (strlen($plaintext) & 0xF) {
337 if (strlen($ciphertext)) {
338 $this->encryptIV
= substr($ciphertext, -16);
340 $this->encryptIV
= mcrypt_generic($this->ecb
, $this->encryptIV
);
341 $this->enbuffer
= substr($plaintext, $last_pos) ^
$this->encryptIV
;
342 $ciphertext.= $this->enbuffer
;
348 if ($this->paddable
) {
349 $plaintext = $this->_pad($plaintext);
352 $ciphertext = mcrypt_generic($this->enmcrypt
, $plaintext);
354 if (!$this->continuousBuffer
) {
355 mcrypt_generic_init($this->enmcrypt
, $this->key
, $this->iv
);
361 return parent
::encrypt($plaintext);
365 * Decrypts a message.
367 * If strlen($ciphertext) is not a multiple of 16, null bytes will be added to the end of the string until it is.
369 * @see Crypt_AES::encrypt()
371 * @param String $ciphertext
373 function decrypt($ciphertext)
375 if ( CRYPT_AES_MODE
== CRYPT_AES_MODE_MCRYPT
) {
376 $changed = $this->changed
;
377 $this->_mcryptSetup();
379 if ($this->mode == CRYPT_AES_MODE_CTR) {
380 $iv = $this->decryptIV;
381 $xor = mcrypt_generic($this->enmcrypt, $this->_generate_xor(strlen($ciphertext), $iv));
382 $plaintext = $ciphertext ^ $xor;
383 if ($this->continuousBuffer) {
384 $this->decryptIV = $iv;
389 if ($this->mode
== 'ncfb') {
391 $this->ecb
= mcrypt_module_open(MCRYPT_RIJNDAEL_128
, '', MCRYPT_MODE_ECB
, '');
392 mcrypt_generic_init($this->ecb
, $this->key
, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
395 if (strlen($this->debuffer
)) {
396 $plaintext = $ciphertext ^
substr($this->decryptIV
, strlen($this->debuffer
));
398 $this->debuffer
.= substr($ciphertext, 0, strlen($plaintext));
399 if (strlen($this->debuffer
) == 16) {
400 $this->decryptIV
= $this->debuffer
;
401 $this->debuffer
= '';
402 mcrypt_generic_init($this->demcrypt
, $this->key
, $this->decryptIV
);
404 $ciphertext = substr($ciphertext, strlen($plaintext));
409 $last_pos = strlen($ciphertext) & 0xFFFFFFF0;
410 $plaintext.= $last_pos ?
mdecrypt_generic($this->demcrypt
, substr($ciphertext, 0, $last_pos)) : '';
412 if (strlen($ciphertext) & 0xF) {
413 if (strlen($plaintext)) {
414 $this->decryptIV
= substr($ciphertext, $last_pos - 16, 16);
416 $this->decryptIV
= mcrypt_generic($this->ecb
, $this->decryptIV
);
417 $this->debuffer
= substr($ciphertext, $last_pos);
418 $plaintext.= $this->debuffer ^
$this->decryptIV
;
424 if ($this->paddable
) {
425 // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
426 // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
427 $ciphertext = str_pad($ciphertext, (strlen($ciphertext) +
15) & 0xFFFFFFF0, chr(0));
430 $plaintext = mdecrypt_generic($this->demcrypt
, $ciphertext);
432 if (!$this->continuousBuffer
) {
433 mcrypt_generic_init($this->demcrypt
, $this->key
, $this->iv
);
436 return $this->paddable ?
$this->_unpad($plaintext) : $plaintext;
439 return parent
::decrypt($ciphertext);
445 * Validates all the variables.
449 function _mcryptSetup()
451 if (!$this->changed
) {
455 if (!$this->explicit_key_length
) {
456 // this just copied from Crypt_Rijndael::_setup()
457 $length = strlen($this->key
) >> 2;
460 } else if ($length < 4) {
464 $this->key_size
= $length << 2;
469 $this->key_size
= 16;
473 $this->key_size
= 24;
477 $this->key_size
= 32;
480 $this->key
= str_pad(substr($this->key
, 0, $this->key_size
), $this->key_size
, chr(0));
481 $this->encryptIV
= $this->decryptIV
= $this->iv
= str_pad(substr($this->iv
, 0, 16), 16, chr(0));
483 if (!isset($this->enmcrypt
)) {
485 //$mode = $this->mode == CRYPT_AES_MODE_CTR ? MCRYPT_MODE_ECB : $this->mode;
487 $this->demcrypt
= mcrypt_module_open(MCRYPT_RIJNDAEL_128
, '', $mode, '');
488 $this->enmcrypt
= mcrypt_module_open(MCRYPT_RIJNDAEL_128
, '', $mode, '');
489 } // else should mcrypt_generic_deinit be called?
491 mcrypt_generic_init($this->demcrypt
, $this->key
, $this->iv
);
492 mcrypt_generic_init($this->enmcrypt
, $this->key
, $this->iv
);
494 $this->changed
= false;
500 * Optimized over Crypt_Rijndael's implementation by means of loop unrolling.
502 * @see Crypt_Rijndael::_encryptBlock()
507 function _encryptBlock($in)
509 $state = unpack('N*word', $in);
518 // addRoundKey and reindex $state
520 $state['word1'] ^
$w[0][0],
521 $state['word2'] ^
$w[0][1],
522 $state['word3'] ^
$w[0][2],
523 $state['word4'] ^
$w[0][3]
526 // shiftRows + subWord + mixColumns + addRoundKey
527 // we could loop unroll this and use if statements to do more rounds as necessary, but, in my tests, that yields
528 // only a marginal improvement. since that also, imho, hinders the readability of the code, i've opted not to do it.
529 for ($round = 1; $round < $this->Nr
; $round++
) {
531 $t0[$state[0] & 0xFF000000] ^
$t1[$state[1] & 0x00FF0000] ^
$t2[$state[2] & 0x0000FF00] ^
$t3[$state[3] & 0x000000FF] ^
$w[$round][0],
532 $t0[$state[1] & 0xFF000000] ^
$t1[$state[2] & 0x00FF0000] ^
$t2[$state[3] & 0x0000FF00] ^
$t3[$state[0] & 0x000000FF] ^
$w[$round][1],
533 $t0[$state[2] & 0xFF000000] ^
$t1[$state[3] & 0x00FF0000] ^
$t2[$state[0] & 0x0000FF00] ^
$t3[$state[1] & 0x000000FF] ^
$w[$round][2],
534 $t0[$state[3] & 0xFF000000] ^
$t1[$state[0] & 0x00FF0000] ^
$t2[$state[1] & 0x0000FF00] ^
$t3[$state[2] & 0x000000FF] ^
$w[$round][3]
541 $this->_subWord($state[0]),
542 $this->_subWord($state[1]),
543 $this->_subWord($state[2]),
544 $this->_subWord($state[3])
547 // shiftRows + addRoundKey
549 ($state[0] & 0xFF000000) ^
($state[1] & 0x00FF0000) ^
($state[2] & 0x0000FF00) ^
($state[3] & 0x000000FF) ^
$this->w
[$this->Nr
][0],
550 ($state[1] & 0xFF000000) ^
($state[2] & 0x00FF0000) ^
($state[3] & 0x0000FF00) ^
($state[0] & 0x000000FF) ^
$this->w
[$this->Nr
][1],
551 ($state[2] & 0xFF000000) ^
($state[3] & 0x00FF0000) ^
($state[0] & 0x0000FF00) ^
($state[1] & 0x000000FF) ^
$this->w
[$this->Nr
][2],
552 ($state[3] & 0xFF000000) ^
($state[0] & 0x00FF0000) ^
($state[1] & 0x0000FF00) ^
($state[2] & 0x000000FF) ^
$this->w
[$this->Nr
][3]
555 return pack('N*', $state[0], $state[1], $state[2], $state[3]);
561 * Optimized over Crypt_Rijndael's implementation by means of loop unrolling.
563 * @see Crypt_Rijndael::_decryptBlock()
568 function _decryptBlock($in)
570 $state = unpack('N*word', $in);
579 // addRoundKey and reindex $state
581 $state['word1'] ^
$dw[$this->Nr
][0],
582 $state['word2'] ^
$dw[$this->Nr
][1],
583 $state['word3'] ^
$dw[$this->Nr
][2],
584 $state['word4'] ^
$dw[$this->Nr
][3]
588 // invShiftRows + invSubBytes + invMixColumns + addRoundKey
589 for ($round = $this->Nr
- 1; $round > 0; $round--) {
591 $dt0[$state[0] & 0xFF000000] ^
$dt1[$state[3] & 0x00FF0000] ^
$dt2[$state[2] & 0x0000FF00] ^
$dt3[$state[1] & 0x000000FF] ^
$dw[$round][0],
592 $dt0[$state[1] & 0xFF000000] ^
$dt1[$state[0] & 0x00FF0000] ^
$dt2[$state[3] & 0x0000FF00] ^
$dt3[$state[2] & 0x000000FF] ^
$dw[$round][1],
593 $dt0[$state[2] & 0xFF000000] ^
$dt1[$state[1] & 0x00FF0000] ^
$dt2[$state[0] & 0x0000FF00] ^
$dt3[$state[3] & 0x000000FF] ^
$dw[$round][2],
594 $dt0[$state[3] & 0xFF000000] ^
$dt1[$state[2] & 0x00FF0000] ^
$dt2[$state[1] & 0x0000FF00] ^
$dt3[$state[0] & 0x000000FF] ^
$dw[$round][3]
598 // invShiftRows + invSubWord + addRoundKey
600 $this->_invSubWord(($state[0] & 0xFF000000) ^
($state[3] & 0x00FF0000) ^
($state[2] & 0x0000FF00) ^
($state[1] & 0x000000FF)) ^
$dw[0][0],
601 $this->_invSubWord(($state[1] & 0xFF000000) ^
($state[0] & 0x00FF0000) ^
($state[3] & 0x0000FF00) ^
($state[2] & 0x000000FF)) ^
$dw[0][1],
602 $this->_invSubWord(($state[2] & 0xFF000000) ^
($state[1] & 0x00FF0000) ^
($state[0] & 0x0000FF00) ^
($state[3] & 0x000000FF)) ^
$dw[0][2],
603 $this->_invSubWord(($state[3] & 0xFF000000) ^
($state[2] & 0x00FF0000) ^
($state[1] & 0x0000FF00) ^
($state[0] & 0x000000FF)) ^
$dw[0][3]
606 return pack('N*', $state[0], $state[1], $state[2], $state[3]);
610 // vim: ts=4:sw=4:et: