\phpseclib\CryptTripleDES

Pure-PHP implementation of Triple DES.

Summary

Methods
Properties
Constants
isValidEngine()
setKey()
_encryptBlock()
_decryptBlock()
_processBlock()
_setupKey()
_setupInlineCrypt()
__construct()
setKeyLength()
getKeyLength()
getBlockLength()
_openssl_ctr_process()
_openssl_ofb_process()
_openssl_translate_mode()
enablePadding()
disablePadding()
setPreferredEngine()
getEngine()
_setEngine()
_pad()
_unpad()
_string_shift()
_string_pop()
_increment_str()
_createInlineCryptFunction()
_getLambdaFunctions()
_hashInlineCryptFunction()
safe_intval()
safe_intval_inline()
setIV()
encrypt()
decrypt()
enableContinuousBuffer()
disableContinuousBuffer()
$block_size
$key_length
$cipher_name_mcrypt
$openssl_mode_names
$cfb_init_len
$des_rounds
$key_length_max
$keys
$shuffle
$ipmap
$invipmap
$sbox1
$sbox2
$sbox3
$sbox4
$sbox5
$sbox6
$sbox7
$sbox8
$WHIRLPOOL_AVAILABLE
$mode
$key
$iv
$encryptIV
$decryptIV
$continuousBuffer
$enbuffer
$debuffer
$enmcrypt
$demcrypt
$enchanged
$dechanged
$ecb
$changed
$padding
$paddable
$engine
$preferredEngine
$cipher_name_openssl
$cipher_name_openssl_ecb
$password_default_salt
$inline_crypt
$use_inline_crypt
$openssl_emulate_ctr
$openssl_options
$explicit_key_length
$skip_key_adjustment
$mode_3cbc
$des
ENCRYPT
DECRYPT
MODE_CTR
MODE_ECB
MODE_CBC
MODE_CFB
MODE_CFB8
MODE_OFB
MODE_STREAM
ENGINE_INTERNAL
ENGINE_MCRYPT
ENGINE_OPENSSL
MODE_3CBC
MODE_CBC3
No protected methods found
No protected properties found
N/A
No private methods found
No private properties found
N/A

Constants

ENCRYPT

ENCRYPT

Contains $keys[self::ENCRYPT]

DECRYPT

DECRYPT

Contains $keys[self::DECRYPT]

MODE_CTR

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

MODE_ECB

Encrypt / decrypt using the Electronic Code Book mode.

MODE_CBC

MODE_CBC

Encrypt / decrypt using the Code Book Chaining mode.

MODE_CFB

MODE_CFB

Encrypt / decrypt using the Cipher Feedback mode.

MODE_CFB8

MODE_CFB8

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

MODE_OFB

MODE_OFB

Encrypt / decrypt using the Output Feedback mode.

MODE_STREAM

MODE_STREAM

Encrypt / decrypt using streaming mode.

ENGINE_INTERNAL

ENGINE_INTERNAL

Base value for the internal implementation $engine switch

ENGINE_MCRYPT

ENGINE_MCRYPT

Base value for the mcrypt implementation $engine switch

ENGINE_OPENSSL

ENGINE_OPENSSL

Base value for the mcrypt implementation $engine switch

MODE_3CBC

MODE_3CBC

Encrypt / decrypt using inner chaining

Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (self::MODE_CBC3).

MODE_CBC3

MODE_CBC3

Encrypt / decrypt using outer chaining

Outer chaining is used by SSH-2 and when the mode is set to \phpseclib\Crypt\Base::MODE_CBC.

Properties

$block_size

$block_size : integer

The Block Length of the block cipher

Type

integer

$key_length

$key_length : integer

Key Length (in bytes)

Type

integer

$cipher_name_mcrypt

$cipher_name_mcrypt : string

The mcrypt specific name of the cipher

Only used if $engine == self::ENGINE_MCRYPT

Type

string

$openssl_mode_names

$openssl_mode_names : array

The OpenSSL names of the cipher / modes

Type

array

$cfb_init_len

$cfb_init_len : integer

Optimizing value while CFB-encrypting

Only relevant if $continuousBuffer enabled and $engine == self::ENGINE_MCRYPT

It's faster to re-init $enmcrypt if $buffer bytes > $cfb_init_len than using the $ecb resource furthermore.

This value depends of the chosen cipher and the time it would be needed for it's initialization [by mcrypt_generic_init()] which, typically, depends on the complexity on its internaly Key-expanding algorithm.

Type

integer

$des_rounds

$des_rounds : integer

Switch for DES/3DES encryption

Used only if $engine == self::ENGINE_INTERNAL

Type

integer

$key_length_max

$key_length_max : string

max possible size of $key

Type

string

$keys

$keys : array

The Key Schedule

Type

array

$shuffle

$shuffle : array

Shuffle table.

For each byte value index, the entry holds an 8-byte string with each byte containing all bits in the same state as the corresponding bit in the index value.

Type

array

$ipmap

$ipmap : array

IP mapping helper table.

Indexing this table with each source byte performs the initial bit permutation.

Type

array

$invipmap

$invipmap : array

Inverse IP mapping helper table.

Indexing this table with a byte value reverses the bit order.

Type

array

$sbox1

$sbox1 : array

Pre-permuted S-box1

Each box ($sbox1-$sbox8) has been vectorized, then each value pre-permuted using the P table: concatenation can then be replaced by exclusive ORs.

Type

array

$sbox2

$sbox2 : array

Pre-permuted S-box2

Type

array

$sbox3

$sbox3 : array

Pre-permuted S-box3

Type

array

$sbox4

$sbox4 : array

Pre-permuted S-box4

Type

array

$sbox5

$sbox5 : array

Pre-permuted S-box5

Type

array

$sbox6

$sbox6 : array

Pre-permuted S-box6

Type

array

$sbox7

$sbox7 : array

Pre-permuted S-box7

Type

array

$sbox8

$sbox8 : array

Pre-permuted S-box8

Type

array

$WHIRLPOOL_AVAILABLE

$WHIRLPOOL_AVAILABLE : boolean

Whirlpool available flag

Type

boolean

$mode

$mode : integer

The Encryption Mode

Type

integer

$key

$key : string

The Key

Type

string

$iv

$iv : string

The Initialization Vector

Type

string

$encryptIV

$encryptIV : string

A "sliding" Initialization Vector

Type

string

$decryptIV

$decryptIV : string

A "sliding" Initialization Vector

Type

string

$continuousBuffer

$continuousBuffer : boolean

Continuous Buffer status

Type

boolean

$enbuffer

$enbuffer : array

Encryption buffer for CTR, OFB and CFB modes

Type

array

$debuffer

$debuffer : array

Decryption buffer for CTR, OFB and CFB modes

Type

array

$enmcrypt

$enmcrypt : resource

mcrypt resource for encryption

The mcrypt resource can be recreated every time something needs to be created or it can be created just once. Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.

Type

resource

$demcrypt

$demcrypt : resource

mcrypt resource for decryption

The mcrypt resource can be recreated every time something needs to be created or it can be created just once. Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.

Type

resource

$enchanged

$enchanged : boolean

Does the enmcrypt resource need to be (re)initialized?

Type

boolean

$dechanged

$dechanged : boolean

Does the demcrypt resource need to be (re)initialized?

Type

boolean

$ecb

$ecb : resource

mcrypt resource for CFB mode

mcrypt's CFB mode, in (and only in) buffered context, is broken, so phpseclib implements the CFB mode by it self, even when the mcrypt php extension is available.

In order to do the CFB-mode work (fast) phpseclib use a separate ECB-mode mcrypt resource.

Type

resource

$changed

$changed : boolean

Does internal cipher state need to be (re)initialized?

Type

boolean

$padding

$padding : boolean

Padding status

Type

boolean

$paddable

$paddable : boolean

Is the mode one that is paddable?

Type

boolean

$engine

$engine : integer

Holds which crypt engine internaly should be use, which will be determined automatically on __construct()

Currently available $engines are:

  • self::ENGINE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required)
  • self::ENGINE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required)
  • self::ENGINE_INTERNAL (slower, pure php-engine, no php-extension required)

Type

integer

$preferredEngine

$preferredEngine : integer

Holds the preferred crypt engine

Type

integer

$cipher_name_openssl

$cipher_name_openssl : string

The openssl specific name of the cipher

Only used if $engine == self::ENGINE_OPENSSL

Type

string

$cipher_name_openssl_ecb

$cipher_name_openssl_ecb : string

The openssl specific name of the cipher in ECB mode

If OpenSSL does not support the mode we're trying to use (CTR) it can still be emulated with ECB mode.

Type

string

$password_default_salt

$password_default_salt : string

The default salt used by setPassword()

Type

string

$inline_crypt

$inline_crypt : Callback

The name of the performance-optimized callback function

Used by encrypt() / decrypt() only if $engine == self::ENGINE_INTERNAL

Type

Callback

$use_inline_crypt

$use_inline_crypt : mixed

Holds whether performance-optimized $inline_crypt() can/should be used.

Type

mixed

$openssl_emulate_ctr

$openssl_emulate_ctr : boolean

If OpenSSL can be used in ECB but not in CTR we can emulate CTR

Type

boolean

$openssl_options

$openssl_options : mixed

Determines what options are passed to openssl_encrypt/decrypt

Type

mixed

$explicit_key_length

$explicit_key_length : boolean

Has the key length explicitly been set or should it be derived from the key, itself?

Type

boolean

$skip_key_adjustment

$skip_key_adjustment : boolean

Don't truncate / null pad key

Type

boolean

$mode_3cbc

$mode_3cbc : boolean

Internal flag whether using self::MODE_3CBC or not

Type

boolean

$des

$des : array

The \phpseclib\Crypt\DES objects

Used only if $mode_3cbc === true

Type

array

Methods

isValidEngine()

isValidEngine(integer  $engine) : boolean

Test for engine validity

This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine()

Parameters

integer $engine

Returns

boolean

setKey()

setKey(string  $key) 

Sets the key.

Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate.

DES also requires that every eighth bit be a parity bit, however, we'll ignore that.

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

Parameters

string $key

_encryptBlock()

_encryptBlock(string  $in) : string

Encrypts a block

Note: Must be extended by the child \phpseclib\Crypt* class

Parameters

string $in

Returns

string

_decryptBlock()

_decryptBlock(string  $in) : string

Decrypts a block

Note: Must be extended by the child \phpseclib\Crypt* class

Parameters

string $in

Returns

string

_processBlock()

_processBlock(string  $block, integer  $mode) : string

Encrypts or decrypts a 64-bit block

$mode should be either self::ENCRYPT or self::DECRYPT. See Feistel.png to get a general idea of what this function does.

Parameters

string $block
integer $mode

Returns

string

_setupKey()

_setupKey() 

Creates the key schedule

Only used if $engine == self::ENGINE_INTERNAL

Note: Must extend by the child \phpseclib\Crypt* class

_setupInlineCrypt()

_setupInlineCrypt() 

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

__construct()

__construct(integer  $mode = \phpseclib\Crypt\Base::MODE_CBC) 

Default Constructor.

Determines whether or not the mcrypt extension should be used.

$mode could be:

  • \phpseclib\Crypt\Base::MODE_ECB

  • \phpseclib\Crypt\Base::MODE_CBC

  • \phpseclib\Crypt\Base::MODE_CTR

  • \phpseclib\Crypt\Base::MODE_CFB

  • \phpseclib\Crypt\Base::MODE_OFB

  • \phpseclib\Crypt\TripleDES::MODE_3CBC

If not explicitly set, \phpseclib\Crypt\Base::MODE_CBC will be used.

Parameters

integer $mode

setKeyLength()

setKeyLength(integer  $length) 

Sets the key length.

Valid key lengths are 64, 128 and 192

Parameters

integer $length

getKeyLength()

getKeyLength() : integer

Returns the current key length in bits

Returns

integer

getBlockLength()

getBlockLength() : integer

Returns the current block length in bits

Returns

integer

_openssl_ctr_process()

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

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

Returns

string

_openssl_ofb_process()

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

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

Returns

string

_openssl_translate_mode()

_openssl_translate_mode() : integer

phpseclib <-> OpenSSL Mode Mapper

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

Returns

integer

enablePadding()

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)

disablePadding()

disablePadding() 

Do not pad packets.

setPreferredEngine()

setPreferredEngine(integer  $engine) : integer

Sets the internal crypt engine

Parameters

integer $engine

Returns

integer

getEngine()

getEngine() 

Returns the engine currently being utilized

_setEngine()

_setEngine() 

Sets the engine as appropriate

_pad()

_pad(string  $text) : string

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

Returns

string

_unpad()

_unpad(string  $text) : string

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

Returns

string

_string_shift()

_string_shift(string  $string, integer  $index = 1) : string

String Shift

Inspired by array_shift

Parameters

string $string
integer $index

Returns

string

_string_pop()

_string_pop(string  $string, integer  $index = 1) : string

String Pop

Inspired by array_pop

Parameters

string $string
integer $index

Returns

string

_increment_str()

_increment_str(string  $var) 

Increment the current string

Parameters

string $var

_createInlineCryptFunction()

_createInlineCryptFunction(array  $cipher_code) : string

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 \phpseclib\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

Returns

string —

(the name of the created callback function)

_getLambdaFunctions()

_getLambdaFunctions() : array

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.

Returns

array —

&$functions

_hashInlineCryptFunction()

_hashInlineCryptFunction(  $bytes) : string

Generates a digest from $bytes

Parameters

$bytes

Returns

string

safe_intval()

safe_intval(string  $x) : integer

Convert float to int

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

Parameters

string $x

Returns

integer

safe_intval_inline()

safe_intval_inline() : string

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

Returns

string

setIV()

setIV(string  $iv) 

Sets the initialization vector. (optional)

SetIV is not required when \phpseclib\Crypt\Base::MODE_ECB is being used. If not explicitly set, it'll be assumed to be all zero's.

Parameters

string $iv

encrypt()

encrypt(string  $plaintext) : string

Encrypts a message.

Parameters

string $plaintext

Returns

string —

$cipertext

decrypt()

decrypt(string  $ciphertext) : string

Decrypts a message.

Parameters

string $ciphertext

Returns

string —

$plaintext

enableContinuousBuffer()

enableContinuousBuffer() 

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

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

echo $des->encrypt(substr($plaintext, 0, 8)); echo $des->encrypt(substr($plaintext, 8, 8)); echo $des->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:

$des->encrypt(substr($plaintext, 0, 8)); echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));

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\DES() 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.

disableContinuousBuffer()

disableContinuousBuffer() 

Treat consecutive packets as if they are a discontinuous buffer.

The default behavior.