[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/inc/phpseclib/ -> Crypt_Base.php (summary)

Base Class for all Crypt_* cipher classes PHP versions 4 and 5

Author: Jim Wigginton
Author: Hans-Juergen Petrich
Copyright: MMVII Jim Wigginton
License: http://www.opensource.org/licenses/mit-license.html MIT License
Link: http://phpseclib.sourceforge.net
Version: 1.0.1
File Size: 1989 lines (76 kb)
Included or required:0 times
Referenced: 1 time
Includes or requires: 0 files

Defines 1 class

Crypt_Base:: (23 methods):
  __construct()
  setIV()
  setKey()
  setPassword()
  encrypt()
  decrypt()
  enablePadding()
  disablePadding()
  enableContinuousBuffer()
  disableContinuousBuffer()
  _encryptBlock()
  _decryptBlock()
  _setupKey()
  _setup()
  _setupMcrypt()
  _pad()
  _unpad()
  _clearBuffers()
  _stringShift()
  _generateXor()
  _setupInlineCrypt()
  _createInlineCryptFunction()
  _getLambdaFunctions()


Class: Crypt_Base  - X-Ref

Base Class for all Crypt_* cipher classes

__construct($mode = CRYPT_MODE_CBC)   X-Ref
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 choosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...)

If not explictly set, CRYPT_MODE_CBC will be used.

param: optional Integer $mode

setIV($iv)   X-Ref
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 explictly set, it'll be assumed
to be all zero's.

Note: Could, but not must, extend by the child Crypt_* class

param: String $iv

setKey($key)   X-Ref
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.

Note: Could, but not must, extend by the child Crypt_* class

param: String $key

setPassword($password, $method = 'pbkdf2')   X-Ref
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}:
$hash, $salt, $count, $dkLen

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

Note: Could, but not must, extend by the child Crypt_* class

param: String $password
param: optional String $method
see: Crypt/Hash.php

encrypt($plaintext)   X-Ref
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.

Note: Could, but not must, extend by the child Crypt_* class

param: String $plaintext
see: Crypt_Base::decrypt()
return: String $cipertext

decrypt($ciphertext)   X-Ref
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.

Note: Could, but not must, extend by the child Crypt_* class

param: String $ciphertext
see: Crypt_Base::encrypt()
return: String $plaintext

enablePadding()   X-Ref
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: Crypt_Base::disablePadding()

disablePadding()   X-Ref
Do not pad packets.

see: Crypt_Base::enablePadding()

enableContinuousBuffer()   X-Ref
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:

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

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

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

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.

Note: Could, but not must, extend by the child Crypt_* class

see: Crypt_Base::disableContinuousBuffer()

disableContinuousBuffer()   X-Ref
Treat consecutive packets as if they are a discontinuous buffer.

The default behavior.

Note: Could, but not must, extend by the child Crypt_* class

see: Crypt_Base::enableContinuousBuffer()

_encryptBlock($in)   X-Ref
Encrypts a block

Note: Must extend by the child Crypt_* class

param: String $in
return: String

_decryptBlock($in)   X-Ref
Decrypts a block

Note: Must extend by the child Crypt_* class

param: String $in
return: String

_setupKey()   X-Ref
Setup the key (expansion)

Only used if $engine == CRYPT_MODE_INTERNAL

Note: Must extend by the child Crypt_* class

see: Crypt_Base::_setup()

_setup()   X-Ref
Setup the CRYPT_MODE_INTERNAL $engine

(re)init, if necessary, the internal cipher $engine and flush all $buffers
Used (only) if $engine == CRYPT_MODE_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

Internally: _setup() is called always before(!) en/decryption.

Note: Could, but not must, extend by the child Crypt_* class

see: setKey()
see: setIV()
see: disableContinuousBuffer()

_setupMcrypt()   X-Ref
Setup the CRYPT_MODE_MCRYPT $engine

(re)init, if necessary, the (ext)mcrypt resources and flush all $buffers
Used (only) if $engine = CRYPT_MODE_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()


Note: Could, but not must, extend by the child Crypt_* class

see: setKey()
see: setIV()
see: disableContinuousBuffer()

_pad($text)   X-Ref
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.

param: String $text
see: Crypt_Base::_unpad()
return: String

_unpad($text)   X-Ref
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.

param: String $text
see: Crypt_Base::_pad()
return: String

_clearBuffers()   X-Ref
Clears internal buffers

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

Note: Could, but not must, extend by the child Crypt_* class


_stringShift(&$string, $index = 1)   X-Ref
String Shift

Inspired by array_shift

param: String $string
param: optional Integer $index
return: String

_generateXor(&$iv, $length)   X-Ref
Generate CTR XOR encryption key

Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
plaintext / ciphertext in CTR mode.

param: String $iv
param: Integer $length
see: Crypt_Base::decrypt()
see: Crypt_Base::encrypt()
return: String $xor

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

Stores the created (or existing) callback function-name
in $this->inline_crypt

Internally for phpseclib developers:

_setupInlineCrypt() would be called only if:

- $engine == CRYPT_MODE_INTERNAL and

- $use_inline_crypt === true

- each time on _setup(), after(!) _setupKey()


This ensures that _setupInlineCrypt() has allways a
full ready2go initializated internal cipher $engine state
where, for example, the keys allready expanded,
keys/block_size calculated and such.

It is, each time if called, the responsibility of _setupInlineCrypt():

- to set $this->inline_crypt to a valid and fully working callback function
as a (faster) replacement for encrypt() / decrypt()

- NOT to create unlimited callback functions (for memory reasons!)
no matter how often _setupInlineCrypt() would be called. At some
point of amount they must be generic re-useable.

- the code of _setupInlineCrypt() it self,
and the generated callback code,
must be, in following order:
- 100% safe
- 100% compatible to encrypt()/decrypt()
- using only php5+ features/lang-constructs/php-extensions if
compatibility (down to php4) or fallback is provided
- readable/maintainable/understandable/commented and... not-cryptic-styled-code :-)
- >= 10% faster than encrypt()/decrypt() [which is, by the way,
the reason for the existence of _setupInlineCrypt() :-)]
- memory-nice
- short (as good as possible)

Note: - _setupInlineCrypt() is using _createInlineCryptFunction() to create the full callback function code.
- In case of using inline crypting, _setupInlineCrypt() must extend by the child Crypt_* class.
- The following variable names are reserved:
- $_*  (all variable names prefixed with an underscore)
- $self (object reference to it self. Do not use $this, but $self instead)
- $in (the content of $in has to en/decrypt by the generated code)
- The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only


see: Crypt_Base::_setup()
see: Crypt_Base::_createInlineCryptFunction()
see: Crypt_Base::encrypt()
see: Crypt_Base::decrypt()

_createInlineCryptFunction($cipher_code)   X-Ref
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:

<code>
+----------------------------------------------------------------------------------------------+
| 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;                                                              |
|     }                                                                                        |
| }                                                                                            |
+----------------------------------------------------------------------------------------------+
</code>

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

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

param: Array $cipher_code
see: Crypt_Base::_setupInlineCrypt()
see: Crypt_Base::encrypt()
see: Crypt_Base::decrypt()
return: String (the name of the created callback function)

_getLambdaFunctions()   X-Ref
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
uniqe value representing, at least, the $mode of
operation (or more... depends of the optimizing level)
for which $mode the lambda function was created.

return: &Array