phpseclib/phpseclib — pull request #259 by petrich (2014-01-30 23:28:41+00:00)
Title: Ciphers: Adding setEngine() and some optimizations

re: https://github.com/phpseclib/phpseclib/pull/255
Hi All,

i made this changes some months ago and its also very well and strong tested.
also all commits which was made in the meantime i merged already together... so @bantu here is the pull request :-)

Main change is the public setEngine() method.

All changes are 100% API and object-behavior compatible to the current (php4) phpseclib-master. So its, imho, a "ready to go" Pull request.

Changlog:

All Ciphers:
- public setEngine([*_MODE_INTERNAL || *_MODE_MCRYPT]) method. Now its (optional) possible to switch the Crypt-Engine non-globaly but on object-level (good for parallel-testing)
- Summarized ~8% codesize reducing
- Replaced md5() hashing for the "$code_hash" digest in the _setupInlineCrypt()'s with a [hopefully :-)] collision-lesser _trapdoor() method. [thx @monnerat for pointing this out and for the code of the _trapdoor() function]
- Example codes: replaced include('') with include_one ''
- Some phpdoc's

Rijndael/AES:
- Some tiny performance optimizations and lower memory-usage for each object
- ~20% codesize reducing for Rijndael.php [before:68kb, after:47kb]

RC2:
- removed the "unaesthetic" :-) setKey('') call at __constructor()'time
- Performance optimization in _setupInlineCrypt()

Description of setEngine() is documented in Base.php:1136
Practical usage:

```php
$aes_1 = new Crypt_AES();
$aes_1->setEngine(CRYPT_AES_MODE_INTERNAL);
// ...
// $aes_1 is forced to use phpseclib's (slower pure php) internal implementaion of the cipher algorithm

$aes_2 = new Crypt_AES();
$aes_2->setEngine(CRYPT_AES_MODE_MCRYPT);
// ...
// $aes_2 is "forced" to use the (faster) mcrypt implementaion of the cipher algorithm.
// If mcrypt is not available/usable then it has no effect and CRYPT_AES_MODE_INTERNAL will transparently used/set.

$aes_3 = new Crypt_AES();
// not calling setEngine()
// ...
// As usual: $aes_3 will use mcrypt if available/usable, otherwhise phpseclib's internal implementaion of the cipher.
```

Note:
setEngine() could called at any time and in random order to all other public object methods, but will reset/clearing the object internal buffer states (ie the buffers from enableContinuousBuffer())
Best practice is imho: setEngine() should be called only if needed (i think main usage will be for testing) and before the first en/decrypt() call.

Greetings All