phpseclib API Documentation
Class

Crypt_RC4

class Crypt_RC4 extends Crypt_Base

Pure-PHP implementation of RC4.

Properties

int $mode The Encryption Mode
int $block_size Block Length of the 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()
string $const_namespace The namespace used by the cipher for its constants.
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
int $key_length Key Length (in bytes)
array $stream The Key Stream for decryption and encryption

Methods

Crypt_Base(int $mode = CRYPT_MODE_CBC)

Default Constructor.

from Crypt_Base
setIV(string $iv)

Dummy function.

setKeyLength(int $length)

Sets the key length

int getKeyLength()

Returns the current key length in bits

from Crypt_Base
int getBlockLength()

Returns the current block length in bits

from Crypt_Base
setKey(string $key)

Sets the key.

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

Sets the password.

from Crypt_Base
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

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

OpenSSL OFB Processor

from Crypt_Base
int _openssl_translate_mode()

phpseclib <-> OpenSSL Mode Mapper

from Crypt_Base
enablePadding()

Pad "packets".

from Crypt_Base
disablePadding()

Do not pad packets.

from Crypt_Base
enableContinuousBuffer()

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

from Crypt_Base
disableContinuousBuffer()

Treat consecutive packets as if they are a discontinuous buffer.

from Crypt_Base
bool isValidEngine(int $engine)

Test for engine validity

setPreferredEngine(int $engine)

Sets the preferred crypt engine

from Crypt_Base
getEngine()

Returns the engine currently being utilized

from Crypt_Base
_setEngine()

Sets the engine as appropriate

from Crypt_Base
string _encryptBlock(string $in)

Encrypts a block

from Crypt_Base
string _decryptBlock(string $in)

Decrypts a block

from Crypt_Base
_setupKey()

Setup the key (expansion)

_setup()

Setup the CRYPTENGINEINTERNAL $engine

from Crypt_Base
_setupMcrypt()

Setup the CRYPTENGINEMCRYPT $engine

from Crypt_Base
string _pad(string $text)

Pads a string

from Crypt_Base
string _unpad(string $text)

Unpads a string.

from Crypt_Base
_clearBuffers()

Clears internal buffers

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

String Shift

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

String Pop

from Crypt_Base
_increment_str(string $var)

Increment the current string

from Crypt_Base
_setupInlineCrypt()

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

from Crypt_Base
string _createInlineCryptFunction(array $cipher_code)

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

from Crypt_Base
array _getLambdaFunctions()

Holds the lambda_functions table (classwide)

from Crypt_Base
string _hashInlineCryptFunction($bytes $bytes)

Generates a digest from $bytes

from Crypt_Base
Crypt_RC4 Crypt_RC4()

Default Constructor.

string _crypt(string $text, int $mode)

Encrypts or decrypts a message.

Details

in Crypt_Base at line 506
public Crypt_Base(int $mode = CRYPT_MODE_CBC)

Default Constructor.

Determines whether or not the mcrypt extension should be used.

$mode could be:

(or the alias constants of the chosen cipher, for example for AES: CRYPTAESMODEECB or CRYPTAESMODECBC ...)

If not explicitly set, CRYPTMODECBC will be used.

Parameters

int $mode

at line 220
public setIV(string $iv)

Dummy function.

Some protocols, such as WEP, prepend an "initialization vector" to the key, effectively creating a new key [1]. If you need to use an initialization vector in this manner, feel free to prepend it to the key, yourself, before calling setKey().

[1] WEP's initialization vectors (IV's) are used in a somewhat insecure way. Since, in that protocol, the IV's are relatively easy to predict, an attack described by {@link http://www.drizzle.com/~aboba/IEEE/rc4_ksaproc.pdf Scott Fluhrer, Itsik Mantin, and Adi Shamir} can be used to quickly guess at the rest of the key. The following links elaborate:

{@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009} {@link http://en.wikipedia.org/wiki/Relatedkeyattack http://en.wikipedia.org/wiki/Relatedkeyattack}

Parameters

string $iv

See also

self::setKey()

at line 232
public setKeyLength(int $length)

Sets the key length

Keys can be between 1 and 256 bytes long.

Parameters

int $length

in Crypt_Base at line 575
public int getKeyLength()

Returns the current key length in bits

Return Value

int

in Crypt_Base at line 586
public int getBlockLength()

Returns the current block length in bits

Return Value

int

in Crypt_Base at line 605
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 Crypt_Base at line 633
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

at line 254
public string encrypt(string $plaintext)

Encrypts a message.

Parameters

string $plaintext

Return Value

string $ciphertext

See also

Crypt_Base::decrypt()
self::_crypt()

at line 274
public string decrypt(string $ciphertext)

Decrypts a message.

$this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)). At least if the continuous buffer is disabled.

Parameters

string $ciphertext

Return Value

string $plaintext

See also

Crypt_Base::encrypt()
self::_crypt()

in Crypt_Base at line 1327
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 CryptBase::encrypt() and CryptBase::decrypt(). Also, OpenSSL doesn't implement CTR for all of it's symmetric ciphers so this function will emulate CTR with ECB when necesary.

Parameters

string $plaintext
string $encryptIV
array $buffer

Return Value

string

See also

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

in Crypt_Base at line 1421
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 CryptBase::encrypt() and CryptBase::decrypt().

Parameters

string $plaintext
string $encryptIV
array $buffer

Return Value

string

See also

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

in Crypt_Base at line 1467
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 Crypt_Base at line 1498
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 Crypt_Base at line 1509
public disablePadding()

Do not pad packets.

See also

self::enablePadding()

in Crypt_Base at line 1552
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 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 Crypt_Base at line 1572
public disableContinuousBuffer()

Treat consecutive packets as if they are a discontinuous buffer.

The default behavior.

See also

self::enableContinuousBuffer()

at line 179
public 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()

in Crypt_Base at line 1661
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::Crypt_Base()

in Crypt_Base at line 1682
public getEngine()

Returns the engine currently being utilized

See also

self::_setEngine()

in Crypt_Base at line 1693
public _setEngine()

Sets the engine as appropriate

See also

self::Crypt_Base()

in Crypt_Base at line 1737
public string _encryptBlock(string $in)

Encrypts a block

Parameters

string $in

Return Value

string

in Crypt_Base at line 1750
public string _decryptBlock(string $in)

Decrypts a block

Parameters

string $in

Return Value

string

at line 289
public _setupKey()

Setup the key (expansion)

See also

Crypt_Base::_setupKey()

in Crypt_Base at line 1793
public _setup()

Setup the CRYPTENGINEINTERNAL $engine

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

_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 Crypt_Base at line 1826
public _setupMcrypt()

Setup the CRYPTENGINEMCRYPT $engine

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

_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 Crypt_Base at line 1872
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 Crypt_Base at line 1901
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 Crypt_Base at line 1926
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 Crypt_Base at line 1949
public string _string_shift(string $string, int $index = 1)

String Shift

Inspired by array_shift

Parameters

string $string
int $index

Return Value

string

in Crypt_Base at line 1966
public string _string_pop(string $string, int $index = 1)

String Pop

Inspired by array_pop

Parameters

string $string
int $index

Return Value

string

in Crypt_Base at line 1981
public _increment_str(string $var)

Increment the current string

Parameters

string $var

See also

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

in Crypt_Base at line 2070
public _setupInlineCrypt()

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_ENGINE_INTERNAL and

- $use_inline_crypt === true

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


This ensures that _setupInlineCrypt() has always 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 also

self::_setup()
self::_createInlineCryptFunction()
self::encrypt()
self::decrypt()

in Crypt_Base at line 2192
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 Crypt_Base at line 2559
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 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 Value

array &$functions

in Crypt_Base at line 2573
public string _hashInlineCryptFunction($bytes $bytes)

Generates a digest from $bytes

Parameters

$bytes $bytes

Return Value

string

See also

self::_setupInlineCrypt()

at line 164
public Crypt_RC4 Crypt_RC4()

Default Constructor.

Determines whether or not the mcrypt extension should be used.

Return Value

Crypt_RC4

See also

Crypt_Base::Crypt_Base()

at line 320
public string _crypt(string $text, int $mode)

Encrypts or decrypts a message.

Parameters

string $text
int $mode

Return Value

string $text

See also

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