ChaCha20
extends Salsa20
in package
Pure-PHP implementation of ChaCha20.
Tags
Table of Contents
Constants
- DECRYPT = 1
- ENCRYPT = 0
- ENGINE_EVAL = 2
- Base value for the eval() implementation $engine switch
- ENGINE_INTERNAL = 1
- Base value for the internal implementation $engine switch
- ENGINE_LIBSODIUM = 5
- Base value for the libsodium implementation $engine switch
- ENGINE_MAP = [self::ENGINE_INTERNAL => 'PHP', self::ENGINE_EVAL => 'Eval', self::ENGINE_MCRYPT => 'mcrypt', self::ENGINE_OPENSSL => 'OpenSSL', self::ENGINE_LIBSODIUM => 'libsodium', self::ENGINE_OPENSSL_GCM => 'OpenSSL (GCM)']
- Engine Reverse Map
- ENGINE_MCRYPT = 3
- Base value for the mcrypt implementation $engine switch
- ENGINE_OPENSSL = 4
- Base value for the openssl implementation $engine switch
- ENGINE_OPENSSL_GCM = 6
- Base value for the openssl / gcm implementation $engine switch
- MODE_CBC = 2
- Encrypt / decrypt using the Code Book Chaining mode.
- MODE_CFB = 3
- Encrypt / decrypt using the Cipher Feedback mode.
- MODE_CFB8 = 38
- Encrypt / decrypt using the Cipher Feedback mode (8bit)
- MODE_CTR = -1
- Encrypt / decrypt using the Counter mode.
- MODE_ECB = 1
- Encrypt / decrypt using the Electronic Code Book mode.
- MODE_GCM = 5
- Encrypt / decrypt using Galois/Counter mode.
- MODE_MAP = ['ctr' => self::MODE_CTR, 'ecb' => self::MODE_ECB, 'cbc' => self::MODE_CBC, 'cfb' => self::MODE_CFB, 'cfb8' => self::MODE_CFB8, 'ofb' => self::MODE_OFB, 'gcm' => self::MODE_GCM, 'stream' => self::MODE_STREAM]
- Mode Map
- MODE_OFB = 4
- Encrypt / decrypt using the Output Feedback mode.
- MODE_STREAM = 6
- Encrypt / decrypt using streaming mode.
Properties
- $aad : string
- Additional authenticated data
- $block_size : int
- Block Length of the cipher
- $cfb_init_len : int
- Optimizing value while CFB-encrypting
- $changed : bool
- Does internal cipher state need to be (re)initialized?
- $cipher_name_mcrypt : string
- The mcrypt specific name of the cipher
- $cipher_name_openssl : string
- The OpenSSL specific name of the cipher
- $cipher_name_openssl_ecb : string
- The openssl specific name of the cipher in ECB mode
- $continuousBuffer : bool
- Continuous Buffer status
- $counter : int
- Counter
- $debuffer : array<string|int, mixed>
- Decryption buffer for continuous mode
- $decryptIV : string
- A "sliding" Initialization Vector
- $enbuffer : array<string|int, mixed>
- Encryption buffer for continuous mode
- $encryptIV : string
- A "sliding" Initialization Vector
- $engine : int
- Holds which crypt engine internaly should be use, which will be determined automatically on __construct()
- $explicit_key_length : bool
- Has the key length explicitly been set or should it be derived from the key, itself?
- $inline_crypt : callable
- The name of the performance-optimized callback function
- $iv : string
- The Initialization Vector
- $key : string
- The Key
- $key_length : int
- Key Length (in bytes)
- $mode : int
- The Encryption Mode
- $newtag : string
- Authentication Tag produced after a round of encryption
- $nonce : string
- Nonce
- $nonIVChanged : bool
- Does Eval engie need to be (re)initialized?
- $oldtag : string
- Authentication Tag to be verified during decryption
- $p1 : string|false
- Part 1 of the state
- $p2 : string|false
- Part 2 of the state
- $poly1305Key : string
- Poly1305 Key
- $usePoly1305 : bool
- Poly1305 Flag
- $usingGeneratedPoly1305Key : bool
- Using Generated Poly1305 Key
- $dechanged : bool
- Does the demcrypt resource need to be (re)initialized?
- $demcrypt : resource
- mcrypt resource for decryption
- $ecb : resource
- mcrypt resource for CFB mode
- $enchanged : bool
- Does the enmcrypt resource need to be (re)initialized?
- $enmcrypt : resource
- mcrypt resource for encryption
- $gcmField : BinaryField
- GCM Binary Field
- $h : Integer
- Hash subkey for GHASH
- $openssl_emulate_ctr : bool
- If OpenSSL can be used in ECB but not in CTR we can emulate CTR
- $origIV : string
- The Original Initialization Vector
- $paddable : bool
- Is the mode one that is paddable?
- $padding : bool
- Padding status
- $password_default_salt : string
- The default salt used by setPassword()
- $poly1305Field : PrimeField
- Poly1305 Prime Field
- $preferredEngine : int
- Holds the preferred crypt engine
- $skip_key_adjustment : bool
- Don't truncate / null pad key
Methods
- __construct() : StreamCipher
- Default Constructor.
- decrypt() : string
- Decrypts a message.
- disableContinuousBuffer() : mixed
- Treat consecutive packets as if they are a discontinuous buffer.
- disablePadding() : mixed
- Do not pad packets.
- enableContinuousBuffer() : mixed
- Treat consecutive "packets" as if they are a continuous buffer.
- enablePadding() : mixed
- Pad "packets".
- enablePoly1305() : mixed
- Enables Poly1305 mode.
- encrypt() : string
- Encrypts a message.
- getBlockLength() : int
- Returns the current block length in bits
- getBlockLengthInBytes() : int
- Returns the current block length in bytes
- getEngine() : mixed
- Returns the engine currently being utilized
- getKeyLength() : int
- Returns the current key length in bits
- getTag() : string
- Get the authentication tag
- isValidEngine() : bool
- Test for engine validity
- setAAD() : mixed
- Sets additional authenticated data
- setCounter() : mixed
- Sets the counter.
- setIV() : mixed
- Sets the initialization vector.
- setKey() : mixed
- Sets the key.
- setKeyLength() : mixed
- Sets the key length.
- setNonce() : mixed
- Sets the nonce.
- setPassword() : bool
- Sets the password.
- setPoly1305Key() : mixed
- Enables Poly1305 mode.
- setPreferredEngine() : mixed
- Sets the preferred crypt engine
- setTag() : mixed
- Sets the authentication tag
- usesIV() : bool
- Stream ciphers not use an IV
- usesNonce() : bool
- Salsa20 uses a nonce
- createInlineCryptFunction() : string
- Creates the performance-optimized function for en/decrypt()
- createPoly1305Key() : mixed
- Creates a Poly1305 key using the method discussed in RFC8439
- decryptBlock() : string
- Decrypts a block
- doubleRound() : mixed
- The doubleround function
- encryptBlock() : string
- Encrypts a block
- getIV() : string
- Get the IV
- isValidEngineHelper() : bool
- Test for engine validity
- leftRotate() : int
- Left Rotate
- nullPad128() : string
- NULL pads a string to be a multiple of 128
- openssl_translate_mode() : string
- phpseclib <-> OpenSSL Mode Mapper
- pad() : string
- Pads a string
- poly1305() : string
- Calculates Poly1305 MAC
- quarterRound() : mixed
- The quarterround function
- safe_intval() : int
- Convert float to int
- safe_intval_inline() : string
- eval()'able string for in-line float to int
- salsa20() : mixed
- The Salsa20 hash function function
- setEngine() : mixed
- Sets the engine as appropriate
- setup() : mixed
- Setup the self::ENGINE_INTERNAL $engine
- setupKey() : mixed
- Setup the key (expansion)
- unpad() : string
- Unpads a string.
- crypt() : string
- Encrypts or decrypts a message.
- decrypt_with_libsodium() : string
- Decrypts a message with libsodium
- encrypt_with_libsodium() : string
- Encrypts a message with libsodium
- ghash() : string
- Performs GHASH operation
- len64() : string
- Returns the bit length of a string in a packed format
- openssl_ctr_process() : string
- OpenSSL CTR Processor
- openssl_ofb_process() : string
- OpenSSL OFB Processor
- pkcs12helper() : string
- PKCS#12 KDF Helper Function
- setupGCM() : mixed
- Sets up GCM parameters
Constants
DECRYPT
public
mixed
DECRYPT
= 1
Tags
ENCRYPT
public
mixed
ENCRYPT
= 0
Tags
ENGINE_EVAL
Base value for the eval() implementation $engine switch
public
mixed
ENGINE_EVAL
= 2
Tags
ENGINE_INTERNAL
Base value for the internal implementation $engine switch
public
mixed
ENGINE_INTERNAL
= 1
Tags
ENGINE_LIBSODIUM
Base value for the libsodium implementation $engine switch
public
mixed
ENGINE_LIBSODIUM
= 5
Tags
ENGINE_MAP
Engine Reverse Map
public
mixed
ENGINE_MAP
= [self::ENGINE_INTERNAL => 'PHP', self::ENGINE_EVAL => 'Eval', self::ENGINE_MCRYPT => 'mcrypt', self::ENGINE_OPENSSL => 'OpenSSL', self::ENGINE_LIBSODIUM => 'libsodium', self::ENGINE_OPENSSL_GCM => 'OpenSSL (GCM)']
Tags
ENGINE_MCRYPT
Base value for the mcrypt implementation $engine switch
public
mixed
ENGINE_MCRYPT
= 3
Tags
ENGINE_OPENSSL
Base value for the openssl implementation $engine switch
public
mixed
ENGINE_OPENSSL
= 4
Tags
ENGINE_OPENSSL_GCM
Base value for the openssl / gcm implementation $engine switch
public
mixed
ENGINE_OPENSSL_GCM
= 6
Tags
MODE_CBC
Encrypt / decrypt using the Code Book Chaining mode.
public
mixed
MODE_CBC
= 2
Tags
MODE_CFB
Encrypt / decrypt using the Cipher Feedback mode.
public
mixed
MODE_CFB
= 3
Tags
MODE_CFB8
Encrypt / decrypt using the Cipher Feedback mode (8bit)
public
mixed
MODE_CFB8
= 38
Tags
MODE_CTR
Encrypt / decrypt using the Counter mode.
public
mixed
MODE_CTR
= -1
Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
Tags
MODE_ECB
Encrypt / decrypt using the Electronic Code Book mode.
public
mixed
MODE_ECB
= 1
Tags
MODE_GCM
Encrypt / decrypt using Galois/Counter mode.
public
mixed
MODE_GCM
= 5
Tags
MODE_MAP
Mode Map
public
mixed
MODE_MAP
= ['ctr' => self::MODE_CTR, 'ecb' => self::MODE_ECB, 'cbc' => self::MODE_CBC, 'cfb' => self::MODE_CFB, 'cfb8' => self::MODE_CFB8, 'ofb' => self::MODE_OFB, 'gcm' => self::MODE_GCM, 'stream' => self::MODE_STREAM]
Tags
MODE_OFB
Encrypt / decrypt using the Output Feedback mode.
public
mixed
MODE_OFB
= 4
Tags
MODE_STREAM
Encrypt / decrypt using streaming mode.
public
mixed
MODE_STREAM
= 6
Tags
Properties
$aad
Additional authenticated data
protected
string
$aad
= ''
Tags
$block_size
Block Length of the cipher
protected
int
$block_size
= 0
Stream ciphers do not have a block size
Tags
$cfb_init_len
Optimizing value while CFB-encrypting
protected
int
$cfb_init_len
= 600
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.
Tags
$changed
Does internal cipher state need to be (re)initialized?
protected
bool
$changed
= true
Tags
$cipher_name_mcrypt
The mcrypt specific name of the cipher
protected
string
$cipher_name_mcrypt
Only used if $engine == self::ENGINE_MCRYPT
Tags
$cipher_name_openssl
The OpenSSL specific name of the cipher
protected
string
$cipher_name_openssl
= 'chacha20'
$cipher_name_openssl_ecb
The openssl specific name of the cipher in ECB mode
protected
string
$cipher_name_openssl_ecb
If OpenSSL does not support the mode we're trying to use (CTR) it can still be emulated with ECB mode.
Tags
$continuousBuffer
Continuous Buffer status
protected
bool
$continuousBuffer
= false
Tags
$counter
Counter
protected
int
$counter
= 0
$debuffer
Decryption buffer for continuous mode
protected
array<string|int, mixed>
$debuffer
$decryptIV
A "sliding" Initialization Vector
protected
string
$decryptIV
Tags
$enbuffer
Encryption buffer for continuous mode
protected
array<string|int, mixed>
$enbuffer
$encryptIV
A "sliding" Initialization Vector
protected
string
$encryptIV
Tags
$engine
Holds which crypt engine internaly should be use, which will be determined automatically on __construct()
protected
int
$engine
Currently available $engines are:
- self::ENGINE_LIBSODIUM (very fast, php-extension: libsodium, extension_loaded('libsodium') required)
- self::ENGINE_OPENSSL_GCM (very fast, php-extension: openssl, extension_loaded('openssl') required)
- 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_EVAL (medium, pure php-engine, no php-extension required)
- self::ENGINE_INTERNAL (slower, pure php-engine, no php-extension required)
Tags
$explicit_key_length
Has the key length explicitly been set or should it be derived from the key, itself?
protected
bool
$explicit_key_length
= false
Tags
$inline_crypt
The name of the performance-optimized callback function
protected
callable
$inline_crypt
Used by encrypt() / decrypt() only if $engine == self::ENGINE_INTERNAL
Tags
$iv
The Initialization Vector
protected
string
$iv
= false
Tags
$key
The Key
protected
string
$key
= false
Tags
$key_length
Key Length (in bytes)
protected
int
$key_length
= 32
$mode
The Encryption Mode
protected
int
$mode
Tags
$newtag
Authentication Tag produced after a round of encryption
protected
string
$newtag
= false
Tags
$nonce
Nonce
protected
string
$nonce
= false
Only used with GCM. We could re-use setIV() but nonce's can be of a different length and toggling between GCM and other modes could be more complicated if we re-used setIV()
Tags
$nonIVChanged
Does Eval engie need to be (re)initialized?
protected
bool
$nonIVChanged
= true
Tags
$oldtag
Authentication Tag to be verified during decryption
protected
string
$oldtag
= false
Tags
$p1
Part 1 of the state
protected
string|false
$p1
= false
$p2
Part 2 of the state
protected
string|false
$p2
= false
$poly1305Key
Poly1305 Key
protected
string
$poly1305Key
Tags
$usePoly1305
Poly1305 Flag
protected
bool
$usePoly1305
= false
Tags
$usingGeneratedPoly1305Key
Using Generated Poly1305 Key
protected
bool
$usingGeneratedPoly1305Key
= false
$dechanged
Does the demcrypt resource need to be (re)initialized?
private
bool
$dechanged
= true
Tags
$demcrypt
mcrypt resource for decryption
private
resource
$demcrypt
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.
Tags
$ecb
mcrypt resource for CFB mode
private
resource
$ecb
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.
Tags
$enchanged
Does the enmcrypt resource need to be (re)initialized?
private
bool
$enchanged
= true
Tags
$enmcrypt
mcrypt resource for encryption
private
resource
$enmcrypt
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.
Tags
$gcmField
GCM Binary Field
private
static BinaryField
$gcmField
Tags
$h
Hash subkey for GHASH
private
Integer
$h
Tags
$openssl_emulate_ctr
If OpenSSL can be used in ECB but not in CTR we can emulate CTR
private
bool
$openssl_emulate_ctr
= false
Tags
$origIV
The Original Initialization Vector
private
string
$origIV
= false
GCM uses the nonce to build the IV but we want to be able to distinguish between nonce-derived IV's and user-set IV's
Tags
$paddable
Is the mode one that is paddable?
private
bool
$paddable
= false
Tags
$padding
Padding status
private
bool
$padding
= true
Tags
$password_default_salt
The default salt used by setPassword()
private
string
$password_default_salt
= 'phpseclib/salt'
Tags
$poly1305Field
Poly1305 Prime Field
private
static PrimeField
$poly1305Field
Tags
$preferredEngine
Holds the preferred crypt engine
private
int
$preferredEngine
Tags
$skip_key_adjustment
Don't truncate / null pad key
private
bool
$skip_key_adjustment
= false
Tags
Methods
__construct()
Default Constructor.
public
__construct() : StreamCipher
Tags
Return values
StreamCipherdecrypt()
Decrypts a message.
public
decrypt(string $ciphertext) : string
$this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)). At least if the continuous buffer is disabled.
Parameters
- $ciphertext : string
Tags
Return values
string —$plaintext
disableContinuousBuffer()
Treat consecutive packets as if they are a discontinuous buffer.
public
disableContinuousBuffer() : mixed
The default behavior.
Tags
disablePadding()
Do not pad packets.
public
disablePadding() : mixed
Tags
enableContinuousBuffer()
Treat consecutive "packets" as if they are a continuous buffer.
public
enableContinuousBuffer() : mixed
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 \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.
Tags
enablePadding()
Pad "packets".
public
enablePadding() : mixed
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)
Tags
enablePoly1305()
Enables Poly1305 mode.
public
enablePoly1305() : mixed
Once enabled Poly1305 cannot be disabled.
Tags
encrypt()
Encrypts a message.
public
encrypt(string $plaintext) : string
Parameters
- $plaintext : string
Tags
Return values
string —$ciphertext
getBlockLength()
Returns the current block length in bits
public
getBlockLength() : int
Tags
Return values
intgetBlockLengthInBytes()
Returns the current block length in bytes
public
getBlockLengthInBytes() : int
Tags
Return values
intgetEngine()
Returns the engine currently being utilized
public
getEngine() : mixed
Tags
getKeyLength()
Returns the current key length in bits
public
getKeyLength() : int
Tags
Return values
intgetTag()
Get the authentication tag
public
getTag([int $length = 16 ]) : string
Only used in GCM or Poly1305 mode
Parameters
- $length : int = 16
-
optional
Tags
Return values
stringisValidEngine()
Test for engine validity
public
isValidEngine(string $engine) : bool
Parameters
- $engine : string
Tags
Return values
boolsetAAD()
Sets additional authenticated data
public
setAAD(string $aad) : mixed
setAAD() is only used by gcm or in poly1305 mode
Parameters
- $aad : string
Tags
setCounter()
Sets the counter.
public
setCounter(int $counter) : mixed
Parameters
- $counter : int
setIV()
Sets the initialization vector.
public
setIV(string $iv) : mixed
setIV() is not required when ecb or gcm modes are being used.
Parameters
- $iv : string
Tags
setKey()
Sets the key.
public
setKey(string $key) : mixed
Parameters
- $key : string
Tags
setKeyLength()
Sets the key length.
public
setKeyLength(int $length) : mixed
Keys with explicitly set lengths need to be treated accordingly
Parameters
- $length : int
Tags
setNonce()
Sets the nonce.
public
setNonce(string $nonce) : mixed
Parameters
- $nonce : string
setPassword()
Sets the password.
public
setPassword(string $password[, string $method = 'pbkdf2' ], array<string|int, string> ...$func_args) : bool
Depending on what $method is set to, setPassword()'s (optional) parameters are as follows: pbkdf2 or pbkdf1: $hash, $salt, $count, $dkLen
Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php
Parameters
- $password : string
- $method : string = 'pbkdf2'
- $func_args : array<string|int, string>
Tags
Return values
boolsetPoly1305Key()
Enables Poly1305 mode.
public
setPoly1305Key([string $key = null ]) : mixed
Once enabled Poly1305 cannot be disabled. If $key is not passed then an attempt to call createPoly1305Key will be made.
Parameters
- $key : string = null
-
optional
Tags
setPreferredEngine()
Sets the preferred crypt engine
public
setPreferredEngine(string $engine) : mixed
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
Parameters
- $engine : string
Tags
setTag()
Sets the authentication tag
public
setTag(string $tag) : mixed
Only used in GCM mode
Parameters
- $tag : string
Tags
usesIV()
Stream ciphers not use an IV
public
usesIV() : bool
Tags
Return values
boolusesNonce()
Salsa20 uses a nonce
public
usesNonce() : bool
Return values
boolcreateInlineCryptFunction()
Creates the performance-optimized function for en/decrypt()
protected
createInlineCryptFunction(array<string|int, mixed> $cipher_code) : string
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 \phpseclib3\Crypt*::_setupInlineCrypt()'s for productive inline $cipher_code's how they works.
Structure of:
$cipher_code = [
'init_crypt' => (string) '', // optional
'init_encrypt' => (string) '', // optional
'init_decrypt' => (string) '', // optional
'encrypt_block' => (string) '', // required
'decrypt_block' => (string) '' // required
];
Parameters
- $cipher_code : array<string|int, mixed>
Tags
Return values
string —(the name of the created callback function)
createPoly1305Key()
Creates a Poly1305 key using the method discussed in RFC8439
protected
createPoly1305Key() : mixed
See https://tools.ietf.org/html/rfc8439#section-2.6.1
decryptBlock()
Decrypts a block
protected
decryptBlock(string $in) : string
Parameters
- $in : string
Return values
stringdoubleRound()
The doubleround function
protected
static doubleRound(int &$x0, int &$x1, int &$x2, int &$x3, int &$x4, int &$x5, int &$x6, int &$x7, int &$x8, int &$x9, int &$x10, int &$x11, int &$x12, int &$x13, int &$x14, int &$x15) : mixed
Parameters
- $x0 : int
-
(by reference)
- $x1 : int
-
(by reference)
- $x2 : int
-
(by reference)
- $x3 : int
-
(by reference)
- $x4 : int
-
(by reference)
- $x5 : int
-
(by reference)
- $x6 : int
-
(by reference)
- $x7 : int
-
(by reference)
- $x8 : int
-
(by reference)
- $x9 : int
-
(by reference)
- $x10 : int
-
(by reference)
- $x11 : int
-
(by reference)
- $x12 : int
-
(by reference)
- $x13 : int
-
(by reference)
- $x14 : int
-
(by reference)
- $x15 : int
-
(by reference)
encryptBlock()
Encrypts a block
protected
encryptBlock(string $in) : string
Parameters
- $in : string
Return values
stringgetIV()
Get the IV
protected
getIV(string $iv) : string
mcrypt requires an IV even if ECB is used
Parameters
- $iv : string
Tags
Return values
stringisValidEngineHelper()
Test for engine validity
protected
isValidEngineHelper(int $engine) : bool
This is mainly just a wrapper to set things up for \phpseclib3\Crypt\Common\SymmetricKey::isValidEngine()
Parameters
- $engine : int
Tags
Return values
boolleftRotate()
Left Rotate
protected
static leftRotate(int $x, int $n) : int
Parameters
- $x : int
- $n : int
Return values
intnullPad128()
NULL pads a string to be a multiple of 128
protected
static nullPad128(string $str) : string
Parameters
- $str : string
Tags
Return values
stringopenssl_translate_mode()
phpseclib <-> OpenSSL Mode Mapper
protected
openssl_translate_mode() : string
May need to be overwritten by classes extending this one in some cases
Tags
Return values
stringpad()
Pads a string
protected
pad(string $text) : 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
- $text : string
Tags
Return values
stringpoly1305()
Calculates Poly1305 MAC
protected
poly1305(string $ciphertext) : string
Parameters
- $ciphertext : string
Tags
Return values
stringquarterRound()
The quarterround function
protected
static quarterRound(int &$a, int &$b, int &$c, int &$d) : mixed
Parameters
- $a : int
- $b : int
- $c : int
- $d : int
safe_intval()
Convert float to int
protected
static safe_intval(string $x) : int
On ARM CPUs converting floats to ints doesn't always work
Parameters
- $x : string
Tags
Return values
intsafe_intval_inline()
eval()'able string for in-line float to int
protected
static safe_intval_inline() : string
Tags
Return values
stringsalsa20()
The Salsa20 hash function function
protected
static salsa20(string $x) : mixed
On my laptop this loop unrolled / function dereferenced version of parent::salsa20 encrypts 1mb of text in 0.65s vs the 0.85s that it takes with the parent method.
If we were free to assume that the host OS would always be 64-bits then the if condition in leftRotate could be eliminated and we could knock this done to 0.60s.
For comparison purposes, RC4 takes 0.16s and AES in CTR mode with the Eval engine takes 0.48s. AES in CTR mode with the PHP engine takes 1.19s. Salsa20 / ChaCha20 do not benefit as much from the Eval approach due to the fact that there are a lot less variables to de-reference, fewer loops to unroll, etc
Parameters
- $x : string
setEngine()
Sets the engine as appropriate
protected
setEngine() : mixed
Tags
setup()
Setup the self::ENGINE_INTERNAL $engine
protected
setup() : mixed
(re)init, if necessary, the internal cipher $engine
_setup() will be called each time if $changed === true typically this happens when using one or more of following public methods:
-
setKey()
-
setNonce()
-
First run of encrypt() / decrypt() with no init-settings
Tags
setupKey()
Setup the key (expansion)
protected
setupKey() : mixed
unpad()
Unpads a string.
protected
unpad(string $text) : 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
- $text : string
Tags
Return values
stringcrypt()
Encrypts or decrypts a message.
private
crypt(string $text, int $mode) : string
Parameters
- $text : string
- $mode : int
Tags
Return values
string —$text
decrypt_with_libsodium()
Decrypts a message with libsodium
private
decrypt_with_libsodium(string $ciphertext) : string
Parameters
- $ciphertext : string
Tags
Return values
string —$text
encrypt_with_libsodium()
Encrypts a message with libsodium
private
encrypt_with_libsodium(string $plaintext) : string
Parameters
- $plaintext : string
Tags
Return values
string —$text
ghash()
Performs GHASH operation
private
ghash(string $x) : string
See https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf#page=20 for more info
Parameters
- $x : string
Tags
Return values
stringlen64()
Returns the bit length of a string in a packed format
private
static len64(string $str) : string
Parameters
- $str : string
Tags
Return values
stringopenssl_ctr_process()
OpenSSL CTR Processor
private
openssl_ctr_process(string $plaintext, string &$encryptIV, array<string|int, mixed> &$buffer) : string
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.
Parameters
- $plaintext : string
- $encryptIV : string
- $buffer : array<string|int, mixed>
Tags
Return values
stringopenssl_ofb_process()
OpenSSL OFB Processor
private
openssl_ofb_process(string $plaintext, string &$encryptIV, array<string|int, mixed> &$buffer) : string
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().
Parameters
- $plaintext : string
- $encryptIV : string
- $buffer : array<string|int, mixed>
Tags
Return values
stringpkcs12helper()
PKCS#12 KDF Helper Function
private
static pkcs12helper(int $n, Hash $hashObj, string $i, string $d, int $count) : string
As discussed here:
Parameters
- $n : int
- $hashObj : Hash
- $i : string
- $d : string
- $count : int
Tags
Return values
string —$a
setupGCM()
Sets up GCM parameters
private
setupGCM() : mixed
See steps 1-2 of https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf#page=23 for more info