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: 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.
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.
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,
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
64 * Include Crypt_Rijndael
66 require_once 'Rijndael.php';
70 * @see Crypt_AES::encrypt()
71 * @see Crypt_AES::decrypt()
74 * Encrypt / decrypt using the Counter mode.
76 * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
78 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
80 define('CRYPT_AES_MODE_CTR', -1);
82 * Encrypt / decrypt using the Electronic Code Book mode.
84 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
86 define('CRYPT_AES_MODE_ECB', 1);
88 * Encrypt / decrypt using the Code Book Chaining mode.
90 * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
92 define('CRYPT_AES_MODE_CBC', 2);
97 * @see Crypt_AES::Crypt_AES()
100 * Toggles the internal implementation
102 define('CRYPT_AES_MODE_INTERNAL', 1);
104 * Toggles the mcrypt implementation
106 define('CRYPT_AES_MODE_MCRYPT', 2);
110 * Pure-PHP implementation of AES.
112 * @author Jim Wigginton <terrafrost@php.net>
117 class Crypt_AES extends Crypt_Rijndael {
119 * mcrypt resource for encryption
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.
124 * @see Crypt_AES::encrypt()
131 * mcrypt resource for decryption
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.
136 * @see Crypt_AES::decrypt()
143 * Default Constructor.
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.
148 * @param optional Integer $mode
152 function Crypt_AES($mode = CRYPT_AES_MODE_CBC)
154 if ( !defined('CRYPT_AES_MODE') ) {
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
160 define('CRYPT_AES_MODE', CRYPT_AES_MODE_MCRYPT);
163 define('CRYPT_AES_MODE', CRYPT_AES_MODE_INTERNAL);
167 switch ( CRYPT_AES_MODE ) {
168 case CRYPT_AES_MODE_MCRYPT:
170 case CRYPT_AES_MODE_ECB:
171 $this->mode = MCRYPT_MODE_ECB;
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.
178 //$this->mode = in_array('ctr', mcrypt_list_modes()) ? 'ctr' : CRYPT_AES_MODE_CTR;
180 case CRYPT_AES_MODE_CBC:
182 $this->mode = MCRYPT_MODE_CBC;
188 case CRYPT_AES_MODE_ECB:
189 $this->mode = CRYPT_RIJNDAEL_MODE_ECB;
191 case CRYPT_AES_MODE_CTR:
192 $this->mode = CRYPT_RIJNDAEL_MODE_CTR;
194 case CRYPT_AES_MODE_CBC:
196 $this->mode = CRYPT_RIJNDAEL_MODE_CBC;
200 if (CRYPT_AES_MODE == CRYPT_AES_MODE_INTERNAL) {
201 parent::Crypt_Rijndael($this->mode);
208 * Since Crypt_AES extends Crypt_Rijndael, this function is, technically, available, but it doesn't do anything.
211 * @param Integer $length
213 function setBlockLength($length)
219 * Encrypts a message.
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
225 * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
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
231 * @see Crypt_AES::decrypt()
233 * @param String $plaintext
235 function encrypt($plaintext)
237 if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
238 $this->_mcryptSetup();
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;
251 if ($this->mode != 'ctr') {
252 $plaintext = $this->_pad($plaintext);
255 $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
257 if (!$this->continuousBuffer) {
258 mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
264 return parent::encrypt($plaintext);
268 * Decrypts a message.
270 * If strlen($ciphertext) is not a multiple of 16, null bytes will be added to the end of the string until it is.
272 * @see Crypt_AES::encrypt()
274 * @param String $ciphertext
276 function decrypt($ciphertext)
278 if ( CRYPT_AES_MODE == CRYPT_AES_MODE_MCRYPT ) {
279 $this->_mcryptSetup();
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;
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));
298 $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
300 if (!$this->continuousBuffer) {
301 mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
304 return $this->mode != 'ctr' ? $this->_unpad($plaintext) : $plaintext;
307 return parent::decrypt($ciphertext);
313 * Validates all the variables.
317 function _mcryptSetup()
319 if (!$this->changed) {
323 if (!$this->explicit_key_length) {
324 // this just copied from Crypt_Rijndael::_setup()
325 $length = strlen($this->key) >> 2;
328 } else if ($length < 4) {
332 $this->key_size = $length << 2;
337 $this->key_size = 16;
341 $this->key_size = 24;
345 $this->key_size = 32;
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));
351 if (!isset($this->enmcrypt)) {
353 //$mode = $this->mode == CRYPT_AES_MODE_CTR ? MCRYPT_MODE_ECB : $this->mode;
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?
359 mcrypt_generic_init($this->demcrypt, $this->key, $this->iv);
360 mcrypt_generic_init($this->enmcrypt, $this->key, $this->iv);
362 $this->changed = false;
368 * Optimized over Crypt_Rijndael's implementation by means of loop unrolling.
370 * @see Crypt_Rijndael::_encryptBlock()
375 function _encryptBlock($in)
377 $state = unpack('N*word', $in);
386 // addRoundKey and reindex $state
388 $state['word1'] ^ $w[0][0],
389 $state['word2'] ^ $w[0][1],
390 $state['word3'] ^ $w[0][2],
391 $state['word4'] ^ $w[0][3]
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++) {
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]
409 $this->_subWord($state[0]),
410 $this->_subWord($state[1]),
411 $this->_subWord($state[2]),
412 $this->_subWord($state[3])
415 // shiftRows + addRoundKey
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]
423 return pack('N*', $state[0], $state[1], $state[2], $state[3]);
429 * Optimized over Crypt_Rijndael's implementation by means of loop unrolling.
431 * @see Crypt_Rijndael::_decryptBlock()
436 function _decryptBlock($in)
438 $state = unpack('N*word', $in);
447 // addRoundKey and reindex $state
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]
456 // invShiftRows + invSubBytes + invMixColumns + addRoundKey
457 for ($round = $this->Nr - 1; $round > 0; $round--) {
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]
466 // invShiftRows + invSubWord + addRoundKey
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]
474 return pack('N*', $state[0], $state[1], $state[2], $state[3]);
478 // vim: ts=4:sw=4:et: