phpseclib API Documentation
Class

phpseclib\Crypt\Twofish

class Twofish extends Base

Pure-PHP implementation of Twofish.

Constants

MODE_CTR

Encrypt / decrypt using the Counter mode.

Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.

MODE_ECB

Encrypt / decrypt using the Electronic Code Book mode.

MODE_CBC

Encrypt / decrypt using the Code Book Chaining mode.

MODE_CFB

Encrypt / decrypt using the Cipher Feedback mode.

MODE_CFB8

Encrypt / decrypt using the Cipher Feedback mode (8bit)

MODE_OFB

Encrypt / decrypt using the Output Feedback mode.

MODE_STREAM

Encrypt / decrypt using streaming mode.

ENGINE_INTERNAL

Base value for the internal implementation $engine switch

ENGINE_MCRYPT

Base value for the mcrypt implementation $engine switch

ENGINE_OPENSSL

Base value for the mcrypt implementation $engine switch

Properties

int $mode The Encryption Mode
int $block_size The Block Length of the block cipher
string $key The Key
string $iv The Initialization Vector
string $encryptIV A "sliding" Initialization Vector
string $decryptIV A "sliding" Initialization Vector
bool $continuousBuffer Continuous Buffer status
array $enbuffer Encryption buffer for CTR, OFB and CFB modes
array $debuffer Decryption buffer for CTR, OFB and CFB modes
resource $enmcrypt mcrypt resource for encryption
resource $demcrypt mcrypt resource for decryption
bool $enchanged Does the enmcrypt resource need to be (re)initialized?
bool $dechanged Does the demcrypt resource need to be (re)initialized?
resource $ecb mcrypt resource for CFB mode
int $cfb_init_len Optimizing value while CFB-encrypting
bool $changed Does internal cipher state need to be (re)initialized?
bool $padding Padding status
bool $paddable Is the mode one that is paddable?
int $engine Holds which crypt engine internaly should be use, which will be determined automatically on __construct()
int $preferredEngine Holds the preferred crypt engine
string $cipher_name_mcrypt The mcrypt specific name of the cipher
string $cipher_name_openssl The openssl specific name of the cipher
string $cipher_name_openssl_ecb The openssl specific name of the cipher in ECB mode
string $password_default_salt The default salt used by setPassword()
Callback $inline_crypt The name of the performance-optimized callback function
mixed $use_inline_crypt Holds whether performance-optimized $inline_crypt() can/should be used.
bool $openssl_emulate_ctr If OpenSSL can be used in ECB but not in CTR we can emulate CTR
mixed $openssl_options Determines what options are passed to openssl_encrypt/decrypt
bool $explicit_key_length Has the key length explicitly been set or should it be derived from the key, itself?
bool $skip_key_adjustment Don't truncate / null pad key
array $q0 Q-Table
array $q1 Q-Table
array $m0 M-Table
array $m1 M-Table
array $m2 M-Table
array $m3 M-Table
array $K The Key Schedule Array
array $S0 The Key depended S-Table 0
array $S1 The Key depended S-Table 1
array $S2 The Key depended S-Table 2
array $S3 The Key depended S-Table 3
array $kl Holds the last used key
int $key_length The Key Length (in bytes)

Methods

__construct(int $mode = self::MODE_CBC)

Default Constructor.

from Base
setIV(string $iv)

Sets the initialization vector.

from Base
setKeyLength(int $length)

Sets the key length.

int getKeyLength()

Returns the current key length in bits

from Base
int getBlockLength()

Returns the current block length in bits

from Base
setKey(string $key)

Sets the key.

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

Sets the password.

from Base
string encrypt(string $plaintext)

Encrypts a message.

from Base
string decrypt(string $ciphertext)

Decrypts a message.

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

OpenSSL CTR Processor

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

OpenSSL OFB Processor

from Base
int _openssl_translate_mode()

phpseclib <-> OpenSSL Mode Mapper

from Base
enablePadding()

Pad "packets".

from Base
disablePadding()

Do not pad packets.

from Base
enableContinuousBuffer()

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

from Base
disableContinuousBuffer()

Treat consecutive packets as if they are a discontinuous buffer.

from Base
bool isValidEngine(int $engine)

Test for engine validity

from Base
setPreferredEngine(int $engine)

Sets the preferred crypt engine

from Base
getEngine()

Returns the engine currently being utilized

from Base
_setEngine()

Sets the engine as appropriate

from Base
_setup()

Setup the self::ENGINE_INTERNAL $engine

from Base
_setupMcrypt()

Setup the self::ENGINE_MCRYPT $engine

from Base
string _pad(string $text)

Pads a string

from Base
string _unpad(string $text)

Unpads a string.

from Base
_clearBuffers()

Clears internal buffers

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

String Shift

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

String Pop

from Base
_increment_str(string $var)

Increment the current string

from Base
_setupInlineCrypt()

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

string _createInlineCryptFunction(array $cipher_code)

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

from Base
array _getLambdaFunctions()

Holds the lambda_functions table (classwide)

from Base
string _hashInlineCryptFunction($bytes $bytes)

Generates a digest from $bytes

from Base
int safe_intval(string $x)

Convert float to int

from Base
string safe_intval_inline()

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

from Base
_setupKey()

Setup the key (expansion)

array _mdsrem(string $A, string $B)

_mdsrem function using by the twofish cipher algorithm

string _encryptBlock(string $in)

Encrypts a block

string _decryptBlock(string $in)

Decrypts a block

Details

in Base at line 476
public __construct(int $mode = self::MODE_CBC)

Default Constructor.

Determines whether or not the mcrypt extension should be used.

$mode could be:

If not explicitly set, self::MODE_CBC will be used.

Parameters

int $mode

in Base at line 515
public setIV(string $iv)

Sets the initialization vector.

(optional)

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

Parameters

string $iv

at line 379
public setKeyLength(int $length)

Sets the key length.

Valid key lengths are 128, 192 or 256 bits

Parameters

int $length

in Base at line 546
public int getKeyLength()

Returns the current key length in bits

Return Value

int

in Base at line 557
public int getBlockLength()

Returns the current block length in bits

Return Value

int

in Base at line 576
public setKey(string $key)

Sets the key.

The min/max length(s) of the key depends on the cipher which is used. If the key not fits the length(s) of the cipher it will paded with null bytes up to the closest valid key length. If the key is more than max length, we trim the excess bits.

If the key is not explicitly set, it'll be assumed to be all null bytes.

Parameters

string $key

in Base at line 604
public 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

Crypt/Hash.php

in Base at line 695
public 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()

in Base at line 1024
public 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()

in Base at line 1348
public 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 Base::encrypt() and 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()

in Base at line 1442
public 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 Base::encrypt() and Base::decrypt().

Parameters

string $plaintext
string $encryptIV
array $buffer

Return Value

string

See also

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

in Base at line 1488
public int _openssl_translate_mode()

phpseclib <-> OpenSSL Mode Mapper

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

Return Value

int

in Base at line 1521
public 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()

in Base at line 1532
public disablePadding()

Do not pad packets.

See also

self::enablePadding()

in Base at line 1575
public 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 \phpseclib\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()

in Base at line 1595
public disableContinuousBuffer()

Treat consecutive packets as if they are a discontinuous buffer.

The default behavior.

See also

self::enableContinuousBuffer()

in Base at line 1618
public bool isValidEngine(int $engine)

Test for engine validity

Parameters

int $engine

Return Value

bool

See also

self::__construct()

in Base at line 1684
public setPreferredEngine(int $engine)

Sets the preferred crypt engine

Currently, $engine could be:

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

Parameters

int $engine

See also

self::__construct()

in Base at line 1705
public getEngine()

Returns the engine currently being utilized

See also

self::_setEngine()

in Base at line 1716
public _setEngine()

Sets the engine as appropriate

See also

self::__construct()

in Base at line 1810
public _setup()

Setup the self::ENGINE_INTERNAL $engine

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

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

See also

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

in Base at line 1843
public _setupMcrypt()

Setup the self::ENGINE_MCRYPT $engine

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

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

See also

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

in Base at line 1890
public 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->blocksize - (strlen($text) % $this->blocksize) bytes are added, each of which is equal to chr($this->blocksize - (strlen($text) % $this->blocksize)

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()

in Base at line 1919
public 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()

in Base at line 1944
public _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()

in Base at line 1967
public string _string_shift(string $string, int $index = 1)

String Shift

Inspired by array_shift

Parameters

string $string
int $index

Return Value

string

in Base at line 1984
public string _string_pop(string $string, int $index = 1)

String Pop

Inspired by array_pop

Parameters

string $string
int $index

Return Value

string

in Base at line 1999
public _increment_str(string $var)

Increment the current string

Parameters

string $var

See also

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

at line 674
public _setupInlineCrypt()

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

See also

\phpseclib\Crypt\Base::_setupInlineCrypt()

in Base at line 2210
public string _createInlineCryptFunction(array $cipher_code)

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

Internally for phpseclib developers:

_createInlineCryptFunction():

Parameters

array $cipher_code

Return Value

string (the name of the created callback function)

See also

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

in Base at line 2628
public 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

in Base at line 2642
public string _hashInlineCryptFunction($bytes $bytes)

Generates a digest from $bytes

Parameters

$bytes $bytes

Return Value

string

See also

self::_setupInlineCrypt()

in Base at line 2678
public int safe_intval(string $x)

Convert float to int

On ARM CPUs converting floats to ints doesn't always work

Parameters

string $x

Return Value

int

in Base at line 2696
public string safe_intval_inline()

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

Return Value

string

at line 401
public _setupKey()

Setup the key (expansion)

See also

\phpseclib\Crypt\Base::_setupKey()

at line 516
public array _mdsrem(string $A, string $B)

_mdsrem function using by the twofish cipher algorithm

Parameters

string $A
string $B

Return Value

array

at line 563
public string _encryptBlock(string $in)

Encrypts a block

Parameters

string $in

Return Value

string

at line 619
public string _decryptBlock(string $in)

Decrypts a block

Parameters

string $in

Return Value

string