DES
class DES extends Base (View source)
Pure-PHP implementation of DES.
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 |
ENCRYPT |
Contains $keys[self::ENCRYPT] |
DECRYPT |
Contains $keys[self::DECRYPT] |
Properties
static bool | $WHIRLPOOL_AVAILABLE | Whirlpool available flag | from Base |
int | $mode | The Encryption Mode | from Base |
int | $block_size | Block Length of the cipher | |
string | $key | The Key | from Base |
string | $iv | The Initialization Vector | from Base |
string | $encryptIV | A "sliding" Initialization Vector | from Base |
string | $decryptIV | A "sliding" Initialization Vector | from Base |
bool | $continuousBuffer | Continuous Buffer status | from Base |
array | $enbuffer | Encryption buffer for CTR, OFB and CFB modes | from Base |
array | $debuffer | Decryption buffer for CTR, OFB and CFB modes | from Base |
resource | $enmcrypt | mcrypt resource for encryption | from Base |
resource | $demcrypt | mcrypt resource for decryption | from Base |
bool | $enchanged | Does the enmcrypt resource need to be (re)initialized? | from Base |
bool | $dechanged | Does the demcrypt resource need to be (re)initialized? | from Base |
resource | $ecb | mcrypt resource for CFB mode | from Base |
int | $cfb_init_len | Optimizing value while CFB-encrypting | |
bool | $changed | Does internal cipher state need to be (re)initialized? | from Base |
bool | $padding | Padding status | from Base |
bool | $paddable | Is the mode one that is paddable? | from Base |
int | $engine | Holds which crypt engine internaly should be use, which will be determined automatically on __construct() | from Base |
int | $preferredEngine | Holds the preferred crypt engine | from Base |
string | $cipher_name_mcrypt | The mcrypt specific name of the cipher | |
string | $cipher_name_openssl | The openssl specific name of the cipher | from Base |
string | $cipher_name_openssl_ecb | The openssl specific name of the cipher in ECB mode | from Base |
string | $password_default_salt | The default salt used by setPassword() | from Base |
callable | $inline_crypt | The name of the performance-optimized callback function | from Base |
mixed | $use_inline_crypt | Holds whether performance-optimized $inline_crypt() can/should be used. | from Base |
bool | $openssl_emulate_ctr | If OpenSSL can be used in ECB but not in CTR we can emulate CTR | from Base |
mixed | $openssl_options | Determines what options are passed to openssl_encrypt/decrypt | from Base |
bool | $explicit_key_length | Has the key length explicitly been set or should it be derived from the key, itself? | from Base |
bool | $skip_key_adjustment | Don't truncate / null pad key | from Base |
int | $key_length | Key Length (in bytes) | |
array | $openssl_mode_names | The OpenSSL names of the cipher / modes | |
int | $des_rounds | Switch for DES/3DES encryption | |
string | $key_length_max | max possible size of $key | |
array | $keys | The Key Schedule | |
array | $shuffle | Shuffle table. | |
array | $ipmap | IP mapping helper table. | |
array | $invipmap | Inverse IP mapping helper table. | |
array | $sbox1 | Pre-permuted S-box1 | |
array | $sbox2 | Pre-permuted S-box2 | |
array | $sbox3 | Pre-permuted S-box3 | |
array | $sbox4 | Pre-permuted S-box4 | |
array | $sbox5 | Pre-permuted S-box5 | |
array | $sbox6 | Pre-permuted S-box6 | |
array | $sbox7 | Pre-permuted S-box7 | |
array | $sbox8 | Pre-permuted S-box8 |
Methods
Sets the key.
OpenSSL CTR Processor
OpenSSL OFB Processor
Treat consecutive packets as if they are a discontinuous buffer.
Test for engine validity
Encrypts a block
Decrypts a block
Creates the key schedule
Setup the performance-optimized function for de/encrypt()
Creates the performance-optimized function for en/decrypt()
Encrypts or decrypts a 64-bit block
Details
in
Base at line 476
__construct(int $mode = self::MODE_CBC)
Default Constructor.
Determines whether or not the mcrypt extension should be used.
$mode could be:
self::MODE_ECB
self::MODE_CBC
self::MODE_CTR
self::MODE_CFB
self::MODE_OFB
If not explicitly set, self::MODE_CBC will be used.
in
Base at line 510
setIV(string $iv)
Sets the initialization vector. (optional)
SetIV is not required when self::MODE_ECB (or ie for AES: \phpseclib\Crypt\AES::MODE_ECB) is being used. If not explicitly set, it'll be assumed to be all zero's.
in
Base at line 528
setKeyLength(int $length)
Sets the key length.
Keys with explicitly set lengths need to be treated accordingly
in
Base at line 541
int
getKeyLength()
Returns the current key length in bits
in
Base at line 552
int
getBlockLength()
Returns the current block length in bits
setKey(string $key)
Sets the key.
Keys can be of any length. DES, itself, uses 64-bit keys (eg. strlen($key) == 8), however, we only use the first eight, if $key has more then eight characters in it, and pad $key with the null byte if it is less then eight characters long.
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 zero's.
in
Base at line 599
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
in
Base at line 690
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.
in
Base at line 1025
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.
in
Base at line 1354
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.
in
Base at line 1448
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().
in
Base at line 1494
int
_openssl_translate_mode()
phpseclib <-> OpenSSL Mode Mapper
May need to be overwritten by classes extending this one in some cases
in
Base at line 1527
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)
in
Base at line 1538
disablePadding()
Do not pad packets.
in
Base at line 1581
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.
in
Base at line 1601
disableContinuousBuffer()
Treat consecutive packets as if they are a discontinuous buffer.
The default behavior.
bool
isValidEngine(int $engine)
Test for engine validity
This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine()
in
Base at line 1693
setPreferredEngine(int $engine)
Sets the preferred crypt engine
Currently, $engine could be:
\phpseclib\Crypt\Base::ENGINE_OPENSSL [very fast]
\phpseclib\Crypt\Base::ENGINE_MCRYPT [fast]
\phpseclib\Crypt\Base::ENGINE_INTERNAL [slow]
If the preferred crypt engine is not available the fastest available one will be used
in
Base at line 1714
getEngine()
Returns the engine currently being utilized
in
Base at line 1725
_setEngine()
Sets the engine as appropriate
string
_encryptBlock(string $in)
Encrypts a block
string
_decryptBlock(string $in)
Decrypts a block
_setupKey()
Creates the key schedule
in
Base at line 1821
_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:
setKey()
setIV()
disableContinuousBuffer()
First run of encrypt() / decrypt() with no init-settings
in
Base at line 1854
_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:
setKey()
setIV()
disableContinuousBuffer()
First run of encrypt() / decrypt()
in
Base at line 1901
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->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.
in
Base at line 1930
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.
in
Base at line 1955
_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 1978
string
_string_shift(string $string, int $index = 1)
String Shift
Inspired by array_shift
in
Base at line 1995
string
_string_pop(string $string, int $index = 1)
String Pop
Inspired by array_pop
in
Base at line 2010
_increment_str(string $var)
Increment the current string
_setupInlineCrypt()
Setup the performance-optimized function for de/encrypt()
in
Base at line 2221
string
_createInlineCryptFunction(array $cipher_code)
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
);
in
Base at line 2635
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.
in
Base at line 2649
string
_hashInlineCryptFunction(string $bytes)
Generates a digest from $bytes
in
Base at line 2685
int
safe_intval(string $x)
Convert float to int
On ARM CPUs converting floats to ints doesn't always work
in
Base at line 2703
string
safe_intval_inline()
eval()'able string for in-line float to int
in
Base at line 2721
do_nothing()
Dummy error handler to suppress mcrypt errors
string
_processBlock(string $block, int $mode)
Encrypts or decrypts a 64-bit block
$mode should be either self::ENCRYPT or self::DECRYPT. See {@link http://en.wikipedia.org/wiki/Image:Feistel.png Feistel.png} to get a general idea of what this function does.