[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/ -> SymmetricKey.php (summary)

Base Class for all \phpseclib3\Crypt\* cipher classes PHP version 5

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

Defines 46 functions

  __construct()
  initialize_static_variables()
  setIV()
  enablePoly1305()
  setPoly1305Key()
  setNonce()
  setAAD()
  usesIV()
  usesNonce()
  getKeyLength()
  getBlockLength()
  getBlockLengthInBytes()
  setKeyLength()
  setKey()
  setPassword()
  pkcs12helper()
  encrypt()
  decrypt()
  getTag()
  setTag()
  getIV()
  openssl_ctr_process()
  openssl_ofb_process()
  openssl_translate_mode()
  enablePadding()
  disablePadding()
  enableContinuousBuffer()
  disableContinuousBuffer()
  isValidEngineHelper()
  isValidEngine()
  setPreferredEngine()
  getEngine()
  setEngine()
  setup()
  pad()
  unpad()
  createInlineCryptFunction()
  safe_intval()
  safe_intval_inline()
  setupGCM()
  ghash()
  len64()
  nullPad128()
  poly1305()
  getMode()
  continuousBufferEnabled()

Functions
Functions that are not part of a class:

__construct($mode)   X-Ref
Default Constructor.

$mode could be:

- ecb

- cbc

- ctr

- cfb

- cfb8

- ofb

- ofb8

- gcm

param: string $mode

initialize_static_variables()   X-Ref
Initialize static variables


setIV($iv)   X-Ref
Sets the initialization vector.

setIV() is not required when ecb or gcm modes are being used.

{@internal Can be overwritten by a sub class, but does not have to be}

param: string $iv

enablePoly1305()   X-Ref
Enables Poly1305 mode.

Once enabled Poly1305 cannot be disabled.


setPoly1305Key($key = null)   X-Ref
Enables Poly1305 mode.

Once enabled Poly1305 cannot be disabled. If $key is not passed then an attempt to call createPoly1305Key
will be made.

param: string $key optional

setNonce($nonce)   X-Ref
Sets the nonce.

setNonce() is only required when gcm is used

param: string $nonce

setAAD($aad)   X-Ref
Sets additional authenticated data

setAAD() is only used by gcm or in poly1305 mode

param: string $aad

usesIV()   X-Ref
Returns whether or not the algorithm uses an IV

return: bool

usesNonce()   X-Ref
Returns whether or not the algorithm uses a nonce

return: bool

getKeyLength()   X-Ref
Returns the current key length in bits

return: int

getBlockLength()   X-Ref
Returns the current block length in bits

return: int

getBlockLengthInBytes()   X-Ref
Returns the current block length in bytes

return: int

setKeyLength($length)   X-Ref
Sets the key length.

Keys with explicitly set lengths need to be treated accordingly

param: int $length

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.

{@internal Could, but not must, extend by the child Crypt_* class}

param: string $key

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

Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php
{@link https://en.wikipedia.org/wiki/Bcrypt bcypt}:
$salt, $rounds, $keylen

This is a modified version of bcrypt used by OpenSSH.

{@internal Could, but not must, extend by the child Crypt_* class}

return: bool
param: string $password
param: string $method
param: int|string ...$func_args
see: Crypt/Hash.php

pkcs12helper($n, $hashObj, $i, $d, $count)   X-Ref
PKCS#12 KDF Helper Function

As discussed here:

{@link https://tools.ietf.org/html/rfc7292#appendix-B}

return: string $a
param: int $n
param: \phpseclib3\Crypt\Hash $hashObj
param: string $i
param: string $d
param: int $count
see: self::setPassword()

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.

{@internal Could, but not must, extend by the child Crypt_* class}

return: string $ciphertext
param: string $plaintext
see: self::decrypt()

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.

{@internal Could, but not must, extend by the child Crypt_* class}

return: string $plaintext
param: string $ciphertext
see: self::encrypt()

getTag($length = 16)   X-Ref
Get the authentication tag

Only used in GCM or Poly1305 mode

return: string
param: int $length optional
see: self::encrypt()

setTag($tag)   X-Ref
Sets the authentication tag

Only used in GCM mode

param: string $tag
see: self::decrypt()

getIV($iv)   X-Ref
Get the IV

mcrypt requires an IV even if ECB is used

return: string
param: string $iv
see: self::encrypt()
see: self::decrypt()

openssl_ctr_process($plaintext, &$encryptIV, &$buffer)   X-Ref
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 SymmetricKey::encrypt()
and SymmetricKey::decrypt(). Also, OpenSSL doesn't implement CTR for all of it's symmetric ciphers so this
function will emulate CTR with ECB when necessary.

return: string
param: string $plaintext
param: string $encryptIV
param: array $buffer
see: self::encrypt()
see: self::decrypt()

openssl_ofb_process($plaintext, &$encryptIV, &$buffer)   X-Ref
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 SymmetricKey::encrypt()
and SymmetricKey::decrypt().

return: string
param: string $plaintext
param: string $encryptIV
param: array $buffer
see: self::encrypt()
see: self::decrypt()

openssl_translate_mode()   X-Ref
phpseclib <-> OpenSSL Mode Mapper

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

return: string

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: self::disablePadding()

disablePadding()   X-Ref
Do not pad packets.

see: self::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 \phpseclib3\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.

{@internal Could, but not must, extend by the child Crypt_* class}

see: self::disableContinuousBuffer()

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

The default behavior.

{@internal Could, but not must, extend by the child Crypt_* class}

see: self::enableContinuousBuffer()

isValidEngineHelper($engine)   X-Ref
Test for engine validity

return: bool
param: int $engine
see: self::__construct()

isValidEngine($engine)   X-Ref
Test for engine validity

return: bool
param: string $engine
see: self::__construct()

setPreferredEngine($engine)   X-Ref
Sets the preferred crypt engine

Currently, $engine could be:

- libsodium[very fast]

- OpenSSL  [very fast]

- mcrypt   [fast]

- Eval     [slow]

- PHP      [slowest]

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

param: string $engine
see: self::__construct()

getEngine()   X-Ref
Returns the engine currently being utilized

see: self::setEngine()

setEngine()   X-Ref
Sets the engine as appropriate

see: self::__construct()

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

- setKey()

- setIV()

- disableContinuousBuffer()

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

{@internal setup() is always called before en/decryption.}

{@internal Could, but not must, extend by the child Crypt_* class}

see: self::setKey()
see: self::setIV()
see: self::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.

return: string
param: string $text
see: self::unpad()

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.

return: string
param: string $text
see: self::pad()

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 \phpseclib3\Crypt\*::_setupInlineCrypt()'s for
productive inline $cipher_code's how they works.

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

return: string (the name of the created callback function)
param: array $cipher_code
see: self::setupInlineCrypt()
see: self::encrypt()
see: self::decrypt()

safe_intval($x)   X-Ref
Convert float to int

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

return: int
param: string $x

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

return: string

setupGCM()   X-Ref
Sets up GCM parameters

See steps 1-2 of https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf#page=23
for more info


ghash($x)   X-Ref
Performs GHASH operation

See https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf#page=20
for more info

return: string
param: string $x
see: self::decrypt()
see: self::encrypt()

len64($str)   X-Ref
Returns the bit length of a string in a packed format

return: string
param: string $str
see: self::decrypt()
see: self::encrypt()
see: self::setupGCM()

nullPad128($str)   X-Ref
NULL pads a string to be a multiple of 128

return: string
param: string $str
see: self::decrypt()
see: self::encrypt()
see: self::setupGCM()

poly1305($text)   X-Ref
Calculates Poly1305 MAC

On my system ChaCha20, with libsodium, takes 0.5s. With this custom Poly1305 implementation
it takes 1.2s.

return: string
param: string $text
see: self::decrypt()
see: self::encrypt()

getMode()   X-Ref
Return the mode

You can do $obj instanceof AES or whatever to get the cipher but you can't do that to get the mode

return: string

continuousBufferEnabled()   X-Ref
Is the continuous buffer enabled?

return: boolean