class Crypt_AES extends Crypt_Rijndael (View source)

Pure-PHP implementation of AES.

Properties

int $mode The Encryption Mode from  Crypt_Base
int $block_size The Block Length of the block cipher from  Crypt_Base
string $key The Key from  Crypt_Base
string $iv The Initialization Vector from  Crypt_Base
string $encryptIV A "sliding" Initialization Vector from  Crypt_Base
string $decryptIV A "sliding" Initialization Vector from  Crypt_Base
bool $continuousBuffer Continuous Buffer status from  Crypt_Base
array $enbuffer Encryption buffer for CTR, OFB and CFB modes from  Crypt_Base
array $debuffer Decryption buffer for CTR, OFB and CFB modes from  Crypt_Base
resource $enmcrypt mcrypt resource for encryption from  Crypt_Base
resource $demcrypt mcrypt resource for decryption from  Crypt_Base
bool $enchanged Does the enmcrypt resource need to be (re)initialized? from  Crypt_Base
bool $dechanged Does the demcrypt resource need to be (re)initialized? from  Crypt_Base
resource $ecb mcrypt resource for CFB mode from  Crypt_Base
int $cfb_init_len Optimizing value while CFB-encrypting from  Crypt_Base
bool $changed Does internal cipher state need to be (re)initialized? from  Crypt_Base
bool $padding Padding status from  Crypt_Base
bool $paddable Is the mode one that is paddable? from  Crypt_Base
int $engine Holds which crypt engine internaly should be use, which will be determined automatically on __construct() from  Crypt_Base
int $preferredEngine Holds the preferred crypt engine from  Crypt_Base
string $cipher_name_mcrypt The mcrypt specific name of the cipher from  Crypt_Rijndael
string $cipher_name_openssl The openssl specific name of the cipher from  Crypt_Base
string $cipher_name_openssl_ecb The openssl specific name of the cipher in ECB mode from  Crypt_Base
string $password_default_salt The default salt used by setPassword() from  Crypt_Rijndael
string $const_namespace The namespace used by the cipher for its constants.
callable $inline_crypt The name of the performance-optimized callback function from  Crypt_Base
mixed $use_inline_crypt Holds whether performance-optimized $inline_crypt() can/should be used. from  Crypt_Base
bool $openssl_emulate_ctr If OpenSSL can be used in ECB but not in CTR we can emulate CTR from  Crypt_Base
mixed $openssl_options Determines what options are passed to openssl_encrypt/decrypt from  Crypt_Base
bool $explicit_key_length Has the key length explicitly been set or should it be derived from the key, itself? from  Crypt_Base
bool $skip_key_adjustment Don't truncate / null pad key from  Crypt_Base
array $w The Key Schedule from  Crypt_Rijndael
array $dw The Inverse Key Schedule from  Crypt_Rijndael
int $Nb The Block Length divided by 32 from  Crypt_Rijndael
int $key_length The Key Length (in bytes) from  Crypt_Rijndael
int $Nk The Key Length divided by 32 from  Crypt_Rijndael
int $Nr The Number of Rounds from  Crypt_Rijndael
array $c Shift offsets from  Crypt_Rijndael
array $kl Holds the last used key- and block_size information from  Crypt_Rijndael

Methods

__construct(int $mode = CRYPT_MODE_CBC)

Default Constructor.

Crypt_Base(int $mode = CRYPT_MODE_CBC)

PHP4 compatible Default Constructor.

setIV(string $iv)

Sets the initialization vector. (optional)

setKeyLength(int $length)

Sets the key length

int
getKeyLength()

Returns the current key length in bits

int
getBlockLength()

Returns the current block length in bits

setKey(string $key)

Sets the key.

bool
setPassword(string $password, string $method = 'pbkdf2')

Sets the password.

string
encrypt(string $plaintext)

Encrypts a message.

string
decrypt(string $ciphertext)

Decrypts a message.

string
_openssl_ctr_process(string $plaintext, string $encryptIV, array $buffer)

OpenSSL CTR Processor

string
_openssl_ofb_process(string $plaintext, string $encryptIV, array $buffer)

OpenSSL OFB Processor

int
_openssl_translate_mode()

phpseclib <-> OpenSSL Mode Mapper

enablePadding()

Pad "packets".

disablePadding()

Do not pad packets.

enableContinuousBuffer()

Treat consecutive "packets" as if they are a continuous buffer.

disableContinuousBuffer()

Treat consecutive packets as if they are a discontinuous buffer.

bool
isValidEngine(int $engine)

Test for engine validity

setPreferredEngine(int $engine)

Sets the preferred crypt engine

getEngine()

Returns the engine currently being utilized

_setEngine()

Sets the engine as appropriate

string
_encryptBlock(string $in)

Encrypts a block

string
_decryptBlock(string $in)

Decrypts a block

_setupKey()

Setup the key (expansion)

_setup()

Setup the CRYPT_ENGINE_INTERNAL $engine

_setupMcrypt()

Setup the CRYPT_ENGINE_MCRYPT $engine

string
_pad(string $text)

Pads a string

string
_unpad(string $text)

Unpads a string.

_clearBuffers()

Clears internal buffers

string
_string_shift(string $string, int $index = 1)

String Shift

string
_string_pop(string $string, int $index = 1)

String Pop

_increment_str(string $var)

Increment the current string

_setupInlineCrypt()

Setup the performance-optimized function for de/encrypt()

string
_createInlineCryptFunction(array $cipher_code)

Creates the performance-optimized function for en/decrypt()

array
_getLambdaFunctions()

Holds the lambda_functions table (classwide)

string
_hashInlineCryptFunction(string $bytes)

Generates a digest from $bytes

int
safe_intval(string $x)

Convert float to int

string
safe_intval_inline()

eval()'able string for in-line float to int

do_nothing()

Dummy error handler to suppress mcrypt errors

setBlockLength(int $length)

Dummy function

_subWord(int $word)

Performs S-Box substitutions

array
_getTables()

Provides the mixColumns and sboxes tables

array
_getInvTables()

Provides the inverse mixColumns and inverse sboxes tables

Details

__construct(int $mode = CRYPT_MODE_CBC)

Default Constructor.

Determines whether or not the mcrypt extension should be used.

$mode could be:

  • CRYPT_MODE_ECB

  • CRYPT_MODE_CBC

  • CRYPT_MODE_CTR

  • CRYPT_MODE_CFB

  • CRYPT_MODE_OFB

(or the alias constants of the chosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...)

If not explicitly set, CRYPT_MODE_CBC will be used.

Parameters

int $mode

Crypt_Base(int $mode = CRYPT_MODE_CBC)

PHP4 compatible Default Constructor.

Parameters

int $mode

See also

\self::__construct()

setIV(string $iv)

Sets the initialization vector. (optional)

SetIV is not required when CRYPT_MODE_ECB (or ie for AES: CRYPT_AES_MODE_ECB) is being used. If not explicitly set, it'll be assumed to be all zero's.

Parameters

string $iv

setKeyLength(int $length)

Sets the key length

Valid key lengths are 128, 192, and 256. If the length is less than 128, it will be rounded up to 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount.

Parameters

int $length

See also

r y

int getKeyLength()

Returns the current key length in bits

Return Value

int

int getBlockLength()

Returns the current block length in bits

Return Value

int

setKey(string $key)

Sets the key.

Rijndael supports five different key lengths, AES only supports three.

Parameters

string $key

See also

r y
setKeyLength()

bool setPassword(string $password, string $method = 'pbkdf2')

Sets the password.

Depending on what $method is set to, setPassword()'s (optional) parameters are as follows: {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2} or pbkdf1: $hash, $salt, $count, $dkLen

Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php

Parameters

string $password
string $method

Return Value

bool

See also

r y

string encrypt(string $plaintext)

Encrypts a message.

$plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's necessary are discussed in the following URL:

{@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}

An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does. strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that length.

Parameters

string $plaintext

Return Value

string $ciphertext

See also

\self::decrypt()

string decrypt(string $ciphertext)

Decrypts a message.

If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until it is.

Parameters

string $ciphertext

Return Value

string $plaintext

See also

\self::encrypt()

string _openssl_ctr_process(string $plaintext, string $encryptIV, array $buffer)

OpenSSL CTR Processor

PHP's OpenSSL bindings do not operate in continuous mode so we'll wrap around it. Since the keystream for CTR is the same for both encrypting and decrypting this function is re-used by both Crypt_Base::encrypt() and Crypt_Base::decrypt(). Also, OpenSSL doesn't implement CTR for all of it's symmetric ciphers so this function will emulate CTR with ECB when necessary.

Parameters

string $plaintext
string $encryptIV
array $buffer

Return Value

string

See also

\self::encrypt()
\self::decrypt()

string _openssl_ofb_process(string $plaintext, string $encryptIV, array $buffer)

OpenSSL OFB Processor

PHP's OpenSSL bindings do not operate in continuous mode so we'll wrap around it. Since the keystream for OFB is the same for both encrypting and decrypting this function is re-used by both Crypt_Base::encrypt() and Crypt_Base::decrypt().

Parameters

string $plaintext
string $encryptIV
array $buffer

Return Value

string

See also

\self::encrypt()
\self::decrypt()

int _openssl_translate_mode()

phpseclib <-> OpenSSL Mode Mapper

May need to be overwritten by classes extending this one in some cases

Return Value

int

enablePadding()

Pad "packets".

Block ciphers working by encrypting between their specified [$this->]block_size at a time If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to pad the input so that it is of the proper length.

Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH, where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is transmitted separately)

See also

\self::disablePadding()

disablePadding()

Do not pad packets.

See also

\self::enablePadding()

enableContinuousBuffer()

Treat consecutive "packets" as if they are a continuous buffer.

Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets will yield different outputs:

echo $rijndael->encrypt(substr($plaintext, 0, 16)); echo $rijndael->encrypt(substr($plaintext, 16, 16)); echo $rijndael->encrypt($plaintext);

The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates another, as demonstrated with the following:

$rijndael->encrypt(substr($plaintext, 0, 16)); echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16))); echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));

With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different outputs. The reason is due to the fact that the initialization vector's change after every encryption / decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.

Put another way, when the continuous buffer is enabled, the state of the Crypt_*() object changes after each encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), however, they are also less intuitive and more likely to cause you problems.

See also

\self::disableContinuousBuffer()

disableContinuousBuffer()

Treat consecutive packets as if they are a discontinuous buffer.

The default behavior.

See also

\self::enableContinuousBuffer()

bool isValidEngine(int $engine)

Test for engine validity

This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine()

Parameters

int $engine

Return Value

bool

See also

Crypt_Base::Crypt_Base

setPreferredEngine(int $engine)

Sets the preferred crypt engine

Currently, $engine could be:

  • CRYPT_ENGINE_OPENSSL [very fast]

  • CRYPT_ENGINE_MCRYPT [fast]

  • CRYPT_ENGINE_INTERNAL [slow]

If the preferred crypt engine is not available the fastest available one will be used

Parameters

int $engine

See also

\self::Crypt_Base()

getEngine()

Returns the engine currently being utilized

See also

\self::_setEngine()

_setEngine()

Sets the engine as appropriate

See also

\self::Crypt_Base()

string _encryptBlock(string $in)

Encrypts a block

Parameters

string $in

Return Value

string

string _decryptBlock(string $in)

Decrypts a block

Parameters

string $in

Return Value

string

_setupKey()

Setup the key (expansion)

_setup()

Setup the CRYPT_ENGINE_INTERNAL $engine

(re)init, if necessary, the internal cipher $engine and flush all $buffers Used (only) if $engine == CRYPT_ENGINE_INTERNAL

_setup() will be called each time if $changed === true typically this happens when using one or more of following public methods:

  • setKey()

  • setIV()

  • disableContinuousBuffer()

  • First run of encrypt() / decrypt() with no init-settings

See also

\self::setKey()
\self::setIV()
\self::disableContinuousBuffer()

_setupMcrypt()

Setup the CRYPT_ENGINE_MCRYPT $engine

(re)init, if necessary, the (ext)mcrypt resources and flush all $buffers Used (only) if $engine = CRYPT_ENGINE_MCRYPT

_setupMcrypt() will be called each time if $changed === true typically this happens when using one or more of following public methods:

  • setKey()

  • setIV()

  • disableContinuousBuffer()

  • First run of encrypt() / decrypt()

See also

\self::setKey()
\self::setIV()
\self::disableContinuousBuffer()

string _pad(string $text)

Pads a string

Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize. $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to chr($this->block_size - (strlen($text) % $this->block_size)

If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless and padding will, hence forth, be enabled.

Parameters

string $text

Return Value

string

See also

\self::_unpad()

string _unpad(string $text)

Unpads a string.

If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong and false will be returned.

Parameters

string $text

Return Value

string

See also

\self::_pad()

_clearBuffers()

Clears internal buffers

Clearing/resetting the internal buffers is done everytime after disableContinuousBuffer() or on cipher $engine (re)init ie after setKey() or setIV()

string _string_shift(string $string, int $index = 1)

String Shift

Inspired by array_shift

Parameters

string $string
int $index

Return Value

string

string _string_pop(string $string, int $index = 1)

String Pop

Inspired by array_pop

Parameters

string $string
int $index

Return Value

string

_increment_str(string $var)

Increment the current string

Parameters

string $var

See also

\self::decrypt()
\self::encrypt()

_setupInlineCrypt()

Setup the performance-optimized function for de/encrypt()

string _createInlineCryptFunction(array $cipher_code)

Creates the performance-optimized function for en/decrypt()

Internally for phpseclib developers:

_createInlineCryptFunction():

  • merge the $cipher_code [setup'ed by _setupInlineCrypt()] with the current [$this->]mode of operation code

  • create the $inline function, which called by encrypt() / decrypt() as its replacement to speed up the en/decryption operations.

  • return the name of the created $inline callback function

  • used to speed up en/decryption

The main reason why can speed up things [up to 50%] this way are:

  • using variables more effective then regular. (ie no use of expensive arrays but integers $k_0, $k_1 ... or even, for example, the pure $key[] values hardcoded)

  • avoiding 1000's of function calls of ie _encryptBlock() but inlining the crypt operations. in the mode of operation for() loop.

  • full loop unroll the (sometimes key-dependent) rounds avoiding this way ++$i counters and runtime-if's etc...

The basic code architectur of the generated $inline en/decrypt() lambda function, in pseudo php, is:

+----------------------------------------------------------------------------------------------+ | callback $inline = create_function: | | lambda_function_0001_crypt_ECB($action, $text) | | { | | INSERT PHP CODE OF: | | $cipher_code['init_crypt']; // general init code. | | // ie: $sbox'es declarations used for | | // encrypt and decrypt'ing. | | | | switch ($action) { | | case 'encrypt': | | INSERT PHP CODE OF: | | $cipher_code['init_encrypt']; // encrypt sepcific init code. | | ie: specified $key or $box | | declarations for encrypt'ing. | | | | foreach ($ciphertext) { | | $in = $block_size of $ciphertext; | | | | INSERT PHP CODE OF: | | $cipher_code['encrypt_block']; // encrypt's (string) $in, which is always: | | // strlen($in) == $this->block_size | | // here comes the cipher algorithm in action | | // for encryption. | | // $cipher_code['encrypt_block'] has to | | // encrypt the content of the $in variable | | | | $plaintext .= $in; | | } | | return $plaintext; | | | | case 'decrypt': | | INSERT PHP CODE OF: | | $cipher_code['init_decrypt']; // decrypt sepcific init code | | ie: specified $key or $box | | declarations for decrypt'ing. | | foreach ($plaintext) { | | $in = $block_size of $plaintext; | | | | INSERT PHP CODE OF: | | $cipher_code['decrypt_block']; // decrypt's (string) $in, which is always | | // strlen($in) == $this->block_size | | // here comes the cipher algorithm in action | | // for decryption. | | // $cipher_code['decrypt_block'] has to | | // decrypt the content of the $in variable | | $ciphertext .= $in; | | } | | return $ciphertext; | | } | | } | +----------------------------------------------------------------------------------------------+

See also the Crypt_*::_setupInlineCrypt()'s for productive inline $cipher_code's how they works.

Structure of: $cipher_code = array( 'init_crypt' => (string) '', // optional 'init_encrypt' => (string) '', // optional 'init_decrypt' => (string) '', // optional 'encrypt_block' => (string) '', // required 'decrypt_block' => (string) '' // required );

Parameters

array $cipher_code

Return Value

string (the name of the created callback function)

See also

\self::_setupInlineCrypt()
\self::encrypt()
\self::decrypt()

array _getLambdaFunctions()

Holds the lambda_functions table (classwide)

Each name of the lambda function, created from _setupInlineCrypt() && _createInlineCryptFunction() is stored, classwide (!), here for reusing.

The string-based index of $function is a classwide unique value representing, at least, the $mode of operation (or more... depends of the optimizing level) for which $mode the lambda function was created.

Return Value

array &$functions

string _hashInlineCryptFunction(string $bytes)

Generates a digest from $bytes

Parameters

string $bytes

Return Value

string

See also

\self::_setupInlineCrypt()

int safe_intval(string $x)

Convert float to int

On 32-bit Linux installs running PHP < 5.3 converting floats to ints doesn't always work

Parameters

string $x

Return Value

int

string safe_intval_inline()

eval()'able string for in-line float to int

Return Value

string

do_nothing()

Dummy error handler to suppress mcrypt errors

setBlockLength(int $length)

Dummy function

Since Crypt_AES extends Crypt_Rijndael, this function is, technically, available, but it doesn't do anything.

Parameters

int $length

See also

Crypt_Rijndael::setBlockLength

_subWord(int $word)

Performs S-Box substitutions

Parameters

int $word

array _getTables()

Provides the mixColumns and sboxes tables

Return Value

array &$tables

See also

r y
r y
r y

array _getInvTables()

Provides the inverse mixColumns and inverse sboxes tables

Return Value

array &$tables

See also

r y
r y
r y