* 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 self::disableContinuousBuffer()
* @access public
* @internal Could, but not must, extend by the child Crypt_* class
*/
function enableContinuousBuffer()
{
if ($this->mode == CRYPT_MODE_ECB) {
return;
}
$this->continuousBuffer = true;
$this->_setEngine();
}
/**
* Treat consecutive packets as if they are a discontinuous buffer.
*
* The default behavior.
*
* @see self::enableContinuousBuffer()
* @access public
* @internal Could, but not must, extend by the child Crypt_* class
*/
function disableContinuousBuffer()
{
if ($this->mode == CRYPT_MODE_ECB) {
return;
}
if (!$this->continuousBuffer) {
return;
}
$this->continuousBuffer = false;
$this->changed = true;
$this->_setEngine();
}
/**
* Test for engine validity
*
* @see self::Crypt_Base()
* @param int $engine
* @access public
* @return bool
*/
function isValidEngine($engine)
{
switch ($engine) {
case CRYPT_ENGINE_OPENSSL:
if ($this->mode == CRYPT_MODE_STREAM && $this->continuousBuffer) {
return false;
}
$this->openssl_emulate_ctr = false;
$result = $this->cipher_name_openssl &&
extension_loaded('openssl') &&
// PHP 5.3.0 - 5.3.2 did not let you set IV's
version_compare(PHP_VERSION, '5.3.3', '>=');
if (!$result) {
return false;
}
// prior to PHP 5.4.0 OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING were not defined. instead of expecting an integer
// $options openssl_encrypt expected a boolean $raw_data.
if (!defined('OPENSSL_RAW_DATA')) {
$this->openssl_options = true;
} else {
$this->openssl_options = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING;
}
$methods = openssl_get_cipher_methods();
if (in_array($this->cipher_name_openssl, $methods)) {
return true;
}
// not all of openssl's symmetric cipher's support ctr. for those
// that don't we'll emulate it
switch ($this->mode) {
case CRYPT_MODE_CTR:
if (in_array($this->cipher_name_openssl_ecb, $methods)) {
$this->openssl_emulate_ctr = true;
return true;
}
}
return false;
case CRYPT_ENGINE_MCRYPT:
return $this->cipher_name_mcrypt &&
extension_loaded('mcrypt') &&
in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms());
case CRYPT_ENGINE_INTERNAL:
return true;
}
return false;
}
/**
* Sets the preferred crypt engine
*
* Currently, $engine could be:
*
* - CRYPT_ENGINE_OPENSSL [very fast]
*
* - CRYPT_ENGINE_MCRYPT [fast]
*
* - CRYPT_ENGINE_INTERNAL [slow]
*
* If the preferred crypt engine is not available the fastest available one will be used
*
* @see self::Crypt_Base()
* @param int $engine
* @access public
*/
function setPreferredEngine($engine)
{
switch ($engine) {
//case CRYPT_ENGINE_OPENSSL:
case CRYPT_ENGINE_MCRYPT:
case CRYPT_ENGINE_INTERNAL:
$this->preferredEngine = $engine;
break;
default:
$this->preferredEngine = CRYPT_ENGINE_OPENSSL;
}
$this->_setEngine();
}
/**
* Returns the engine currently being utilized
*
* @see self::_setEngine()
* @access public
*/
function getEngine()
{
return $this->engine;
}
/**
* Sets the engine as appropriate
*
* @see self::Crypt_Base()
* @access private
*/
function _setEngine()
{
$this->engine = null;
$candidateEngines = array(
$this->preferredEngine,
CRYPT_ENGINE_OPENSSL,
CRYPT_ENGINE_MCRYPT
);
foreach ($candidateEngines as $engine) {
if ($this->isValidEngine($engine)) {
$this->engine = $engine;
break;
}
}
if (!$this->engine) {
$this->engine = CRYPT_ENGINE_INTERNAL;
}
if ($this->engine != CRYPT_ENGINE_MCRYPT && $this->enmcrypt) {
// Closing the current mcrypt resource(s). _mcryptSetup() will, if needed,
// (re)open them with the module named in $this->cipher_name_mcrypt
mcrypt_module_close($this->enmcrypt);
mcrypt_module_close($this->demcrypt);
$this->enmcrypt = null;
$this->demcrypt = null;
if ($this->ecb) {
mcrypt_module_close($this->ecb);
$this->ecb = null;
}
}
$this->changed = true;
}
/**
* Encrypts a block
*
* @access private
* @param string $in
* @return string
* @internal Must be extended by the child Crypt_* class
*/
function _encryptBlock($in)
{
user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
}
/**
* Decrypts a block
*
* @access private
* @param string $in
* @return string
* @internal Must be extended by the child Crypt_* class
*/
function _decryptBlock($in)
{
user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
}
/**
* Setup the key (expansion)
*
* Only used if $engine == CRYPT_ENGINE_INTERNAL
*
* @see self::_setup()
* @access private
* @internal Must be extended by the child Crypt_* class
*/
function _setupKey()
{
user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
}
/**
* Setup the CRYPT_ENGINE_INTERNAL $engine
*
* (re)init, if necessary, the internal cipher $engine and flush all $buffers
* Used (only) if $engine == CRYPT_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
*
* @see self::setKey()
* @see self::setIV()
* @see self::disableContinuousBuffer()
* @access private
* @internal _setup() is always called before en/decryption.
* @internal Could, but not must, extend by the child Crypt_* class
*/
function _setup()
{
$this->_clearBuffers();
$this->_setupKey();
if ($this->use_inline_crypt) {
$this->_setupInlineCrypt();
}
}
/**
* Setup the CRYPT_ENGINE_MCRYPT $engine
*
* (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers
* Used (only) if $engine = CRYPT_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()
*
* @see self::setKey()
* @see self::setIV()
* @see self::disableContinuousBuffer()
* @access private
* @internal Could, but not must, extend by the child Crypt_* class
*/
function _setupMcrypt()
{
$this->_clearBuffers();
$this->enchanged = $this->dechanged = true;
if (!isset($this->enmcrypt)) {
static $mcrypt_modes = array(
CRYPT_MODE_CTR => 'ctr',
CRYPT_MODE_ECB => MCRYPT_MODE_ECB,
CRYPT_MODE_CBC => MCRYPT_MODE_CBC,
CRYPT_MODE_CFB => 'ncfb',
CRYPT_MODE_OFB => MCRYPT_MODE_NOFB,
CRYPT_MODE_STREAM => MCRYPT_MODE_STREAM,
);
$this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
$this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
// we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
// to workaround mcrypt's broken ncfb implementation in buffered mode
// see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
if ($this->mode == CRYPT_MODE_CFB) {
$this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
}
} // else should mcrypt_generic_deinit be called?
if ($this->mode == CRYPT_MODE_CFB) {
mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
}
}
/**
* 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.
*
* @see self::_unpad()
* @param string $text
* @access private
* @return string
*/
function _pad($text)
{
$length = strlen($text);
if (!$this->padding) {
if ($length % $this->block_size == 0) {
return $text;
} else {
user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})");
$this->padding = true;
}
}
$pad = $this->block_size - ($length % $this->block_size);
return str_pad($text, $length + $pad, chr($pad));
}
/**
* 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.
*
* @see self::_pad()
* @param string $text
* @access private
* @return string
*/
function _unpad($text)
{
if (!$this->padding) {
return $text;
}
$length = ord($text[strlen($text) - 1]);
if (!$length || $length > $this->block_size) {
return false;
}
return substr($text, 0, -$length);
}
/**
* Clears internal buffers
*
* Clearing/resetting the internal buffers is done everytime
* after disableContinuousBuffer() or on cipher $engine (re)init
* ie after setKey() or setIV()
*
* @access public
* @internal Could, but not must, extend by the child Crypt_* class
*/
function _clearBuffers()
{
$this->enbuffer = $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
// mcrypt's handling of invalid's $iv:
// $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size);
$this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0");
if (!$this->skip_key_adjustment) {
$this->key = str_pad(substr($this->key, 0, $this->key_length), $this->key_length, "\0");
}
}
/**
* String Shift
*
* Inspired by array_shift
*
* @param string $string
* @param int $index
* @access private
* @return string
*/
function _string_shift(&$string, $index = 1)
{
$substr = substr($string, 0, $index);
$string = substr($string, $index);
return $substr;
}
/**
* String Pop
*
* Inspired by array_pop
*
* @param string $string
* @param int $index
* @access private
* @return string
*/
function _string_pop(&$string, $index = 1)
{
$substr = substr($string, -$index);
$string = substr($string, 0, -$index);
return $substr;
}
/**
* Increment the current string
*
* @see self::decrypt()
* @see self::encrypt()
* @param string $var
* @access private
*/
function _increment_str(&$var)
{
for ($i = 4; $i <= strlen($var); $i+= 4) {
$temp = substr($var, -$i, 4);
switch ($temp) {
case "\xFF\xFF\xFF\xFF":
$var = substr_replace($var, "\x00\x00\x00\x00", -$i, 4);
break;
case "\x7F\xFF\xFF\xFF":
$var = substr_replace($var, "\x80\x00\x00\x00", -$i, 4);
return;
default:
$temp = unpack('Nnum', $temp);
$var = substr_replace($var, pack('N', $temp['num'] + 1), -$i, 4);
return;
}
}
$remainder = strlen($var) % 4;
if ($remainder == 0) {
return;
}
$temp = unpack('Nnum', str_pad(substr($var, 0, $remainder), 4, "\0", STR_PAD_LEFT));
$temp = substr(pack('N', $temp['num'] + 1), -$remainder);
$var = substr_replace($var, $temp, 0, $remainder);
}
/**
* 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 self::_setup()
* @see self::_createInlineCryptFunction()
* @see self::encrypt()
* @see self::decrypt()
* @access private
* @internal If a Crypt_* class providing inline crypting it must extend _setupInlineCrypt()
*/
function _setupInlineCrypt()
{
// If, for any reason, an extending Crypt_Base() Crypt_* class
// not using inline crypting then it must be ensured that: $this->use_inline_crypt = false
// ie in the class var declaration of $use_inline_crypt in general for the Crypt_* class,
// in the constructor at object instance-time
// or, if it's runtime-specific, at runtime
$this->use_inline_crypt = false;
}
/**
* 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 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
* );
*
*
* @see self::_setupInlineCrypt()
* @see self::encrypt()
* @see self::decrypt()
* @param array $cipher_code
* @access private
* @return string (the name of the created callback function)
*/
function _createInlineCryptFunction($cipher_code)
{
$block_size = $this->block_size;
// optional
$init_crypt = isset($cipher_code['init_crypt']) ? $cipher_code['init_crypt'] : '';
$init_encrypt = isset($cipher_code['init_encrypt']) ? $cipher_code['init_encrypt'] : '';
$init_decrypt = isset($cipher_code['init_decrypt']) ? $cipher_code['init_decrypt'] : '';
// required
$encrypt_block = $cipher_code['encrypt_block'];
$decrypt_block = $cipher_code['decrypt_block'];
// Generating mode of operation inline code,
// merged with the $cipher_code algorithm
// for encrypt- and decryption.
switch ($this->mode) {
case CRYPT_MODE_ECB:
$encrypt = $init_encrypt . '
$_ciphertext = "";
$_plaintext_len = strlen($_text);
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
$in = substr($_text, $_i, '.$block_size.');
'.$encrypt_block.'
$_ciphertext.= $in;
}
return $_ciphertext;
';
$decrypt = $init_decrypt . '
$_plaintext = "";
$_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
$_ciphertext_len = strlen($_text);
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
$in = substr($_text, $_i, '.$block_size.');
'.$decrypt_block.'
$_plaintext.= $in;
}
return $self->_unpad($_plaintext);
';
break;
case CRYPT_MODE_CTR:
$encrypt = $init_encrypt . '
$_ciphertext = "";
$_plaintext_len = strlen($_text);
$_xor = $self->encryptIV;
$_buffer = &$self->enbuffer;
if (strlen($_buffer["ciphertext"])) {
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
$_block = substr($_text, $_i, '.$block_size.');
if (strlen($_block) > strlen($_buffer["ciphertext"])) {
$in = $_xor;
'.$encrypt_block.'
$self->_increment_str($_xor);
$_buffer["ciphertext"].= $in;
}
$_key = $self->_string_shift($_buffer["ciphertext"], '.$block_size.');
$_ciphertext.= $_block ^ $_key;
}
} else {
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
$_block = substr($_text, $_i, '.$block_size.');
$in = $_xor;
'.$encrypt_block.'
$self->_increment_str($_xor);
$_key = $in;
$_ciphertext.= $_block ^ $_key;
}
}
if ($self->continuousBuffer) {
$self->encryptIV = $_xor;
if ($_start = $_plaintext_len % '.$block_size.') {
$_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
}
}
return $_ciphertext;
';
$decrypt = $init_encrypt . '
$_plaintext = "";
$_ciphertext_len = strlen($_text);
$_xor = $self->decryptIV;
$_buffer = &$self->debuffer;
if (strlen($_buffer["ciphertext"])) {
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
$_block = substr($_text, $_i, '.$block_size.');
if (strlen($_block) > strlen($_buffer["ciphertext"])) {
$in = $_xor;
'.$encrypt_block.'
$self->_increment_str($_xor);
$_buffer["ciphertext"].= $in;
}
$_key = $self->_string_shift($_buffer["ciphertext"], '.$block_size.');
$_plaintext.= $_block ^ $_key;
}
} else {
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
$_block = substr($_text, $_i, '.$block_size.');
$in = $_xor;
'.$encrypt_block.'
$self->_increment_str($_xor);
$_key = $in;
$_plaintext.= $_block ^ $_key;
}
}
if ($self->continuousBuffer) {
$self->decryptIV = $_xor;
if ($_start = $_ciphertext_len % '.$block_size.') {
$_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
}
}
return $_plaintext;
';
break;
case CRYPT_MODE_CFB:
$encrypt = $init_encrypt . '
$_ciphertext = "";
$_buffer = &$self->enbuffer;
if ($self->continuousBuffer) {
$_iv = &$self->encryptIV;
$_pos = &$_buffer["pos"];
} else {
$_iv = $self->encryptIV;
$_pos = 0;
}
$_len = strlen($_text);
$_i = 0;
if ($_pos) {
$_orig_pos = $_pos;
$_max = '.$block_size.' - $_pos;
if ($_len >= $_max) {
$_i = $_max;
$_len-= $_max;
$_pos = 0;
} else {
$_i = $_len;
$_pos+= $_len;
$_len = 0;
}
$_ciphertext = substr($_iv, $_orig_pos) ^ $_text;
$_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i);
}
while ($_len >= '.$block_size.') {
$in = $_iv;
'.$encrypt_block.';
$_iv = $in ^ substr($_text, $_i, '.$block_size.');
$_ciphertext.= $_iv;
$_len-= '.$block_size.';
$_i+= '.$block_size.';
}
if ($_len) {
$in = $_iv;
'.$encrypt_block.'
$_iv = $in;
$_block = $_iv ^ substr($_text, $_i);
$_iv = substr_replace($_iv, $_block, 0, $_len);
$_ciphertext.= $_block;
$_pos = $_len;
}
return $_ciphertext;
';
$decrypt = $init_encrypt . '
$_plaintext = "";
$_buffer = &$self->debuffer;
if ($self->continuousBuffer) {
$_iv = &$self->decryptIV;
$_pos = &$_buffer["pos"];
} else {
$_iv = $self->decryptIV;
$_pos = 0;
}
$_len = strlen($_text);
$_i = 0;
if ($_pos) {
$_orig_pos = $_pos;
$_max = '.$block_size.' - $_pos;
if ($_len >= $_max) {
$_i = $_max;
$_len-= $_max;
$_pos = 0;
} else {
$_i = $_len;
$_pos+= $_len;
$_len = 0;
}
$_plaintext = substr($_iv, $_orig_pos) ^ $_text;
$_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i);
}
while ($_len >= '.$block_size.') {
$in = $_iv;
'.$encrypt_block.'
$_iv = $in;
$cb = substr($_text, $_i, '.$block_size.');
$_plaintext.= $_iv ^ $cb;
$_iv = $cb;
$_len-= '.$block_size.';
$_i+= '.$block_size.';
}
if ($_len) {
$in = $_iv;
'.$encrypt_block.'
$_iv = $in;
$_plaintext.= $_iv ^ substr($_text, $_i);
$_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len);
$_pos = $_len;
}
return $_plaintext;
';
break;
case CRYPT_MODE_OFB:
$encrypt = $init_encrypt . '
$_ciphertext = "";
$_plaintext_len = strlen($_text);
$_xor = $self->encryptIV;
$_buffer = &$self->enbuffer;
if (strlen($_buffer["xor"])) {
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
$_block = substr($_text, $_i, '.$block_size.');
if (strlen($_block) > strlen($_buffer["xor"])) {
$in = $_xor;
'.$encrypt_block.'
$_xor = $in;
$_buffer["xor"].= $_xor;
}
$_key = $self->_string_shift($_buffer["xor"], '.$block_size.');
$_ciphertext.= $_block ^ $_key;
}
} else {
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
$in = $_xor;
'.$encrypt_block.'
$_xor = $in;
$_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
}
$_key = $_xor;
}
if ($self->continuousBuffer) {
$self->encryptIV = $_xor;
if ($_start = $_plaintext_len % '.$block_size.') {
$_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
}
}
return $_ciphertext;
';
$decrypt = $init_encrypt . '
$_plaintext = "";
$_ciphertext_len = strlen($_text);
$_xor = $self->decryptIV;
$_buffer = &$self->debuffer;
if (strlen($_buffer["xor"])) {
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
$_block = substr($_text, $_i, '.$block_size.');
if (strlen($_block) > strlen($_buffer["xor"])) {
$in = $_xor;
'.$encrypt_block.'
$_xor = $in;
$_buffer["xor"].= $_xor;
}
$_key = $self->_string_shift($_buffer["xor"], '.$block_size.');
$_plaintext.= $_block ^ $_key;
}
} else {
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
$in = $_xor;
'.$encrypt_block.'
$_xor = $in;
$_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
}
$_key = $_xor;
}
if ($self->continuousBuffer) {
$self->decryptIV = $_xor;
if ($_start = $_ciphertext_len % '.$block_size.') {
$_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
}
}
return $_plaintext;
';
break;
case CRYPT_MODE_STREAM:
$encrypt = $init_encrypt . '
$_ciphertext = "";
'.$encrypt_block.'
return $_ciphertext;
';
$decrypt = $init_decrypt . '
$_plaintext = "";
'.$decrypt_block.'
return $_plaintext;
';
break;
// case CRYPT_MODE_CBC:
default:
$encrypt = $init_encrypt . '
$_ciphertext = "";
$_plaintext_len = strlen($_text);
$in = $self->encryptIV;
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
$in = substr($_text, $_i, '.$block_size.') ^ $in;
'.$encrypt_block.'
$_ciphertext.= $in;
}
if ($self->continuousBuffer) {
$self->encryptIV = $in;
}
return $_ciphertext;
';
$decrypt = $init_decrypt . '
$_plaintext = "";
$_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
$_ciphertext_len = strlen($_text);
$_iv = $self->decryptIV;
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
$in = $_block = substr($_text, $_i, '.$block_size.');
'.$decrypt_block.'
$_plaintext.= $in ^ $_iv;
$_iv = $_block;
}
if ($self->continuousBuffer) {
$self->decryptIV = $_iv;
}
return $self->_unpad($_plaintext);
';
break;
}
// Create the $inline function and return its name as string. Ready to run!
return create_function('$_action, &$self, $_text', $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }');
}
/**
* 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.
*
* @access private
* @return array &$functions
*/
function &_getLambdaFunctions()
{
static $functions = array();
return $functions;
}
/**
* Generates a digest from $bytes
*
* @see self::_setupInlineCrypt()
* @access private
* @param $bytes
* @return string
*/
function _hashInlineCryptFunction($bytes)
{
if (!defined('CRYPT_BASE_WHIRLPOOL_AVAILABLE')) {
define('CRYPT_BASE_WHIRLPOOL_AVAILABLE', (bool)(extension_loaded('hash') && in_array('whirlpool', hash_algos())));
}
$result = '';
$hash = $bytes;
switch (true) {
case CRYPT_BASE_WHIRLPOOL_AVAILABLE:
foreach (str_split($bytes, 64) as $t) {
$hash = hash('whirlpool', $hash, true);
$result .= $t ^ $hash;
}
return $result . hash('whirlpool', $hash, true);
default:
$len = strlen($bytes);
for ($i = 0; $i < $len; $i+=20) {
$t = substr($bytes, $i, 20);
$hash = pack('H*', sha1($hash));
$result .= $t ^ $hash;
}
return $result . pack('H*', sha1($hash));
}
}
}
phpseclib-1.0.1/phpseclib/Crypt/Blowfish.php 0000664 0000000 0000000 00000070134 12647215700 0021033 0 ustar 00root root 0000000 0000000
* setKey('12345678901234567890123456789012');
*
* $plaintext = str_repeat('a', 1024);
*
* echo $blowfish->decrypt($blowfish->encrypt($plaintext));
* ?>
*
*
* LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @category Crypt
* @package Crypt_Blowfish
* @author Jim Wigginton
* createKey());
*
* $plaintext = 'terrafrost';
*
* $rsa->loadKey($privatekey);
* $signature = $rsa->sign($plaintext);
*
* $rsa->loadKey($publickey);
* echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
* ?>
*
*
* LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @category Crypt
* @package Crypt_RSA
* @author Jim Wigginton ' . base64_encode($raw['prime1']) . "
\r\n" . '' . base64_encode($raw['prime2']) . "\r\n" . '