PageRenderTime 6ms CodeModel.GetById 48ms app.highlight 46ms RepoModel.GetById 1ms app.codeStats 0ms

/apps/files_external/3rdparty/phpseclib/phpseclib/Crypt/TripleDES.php

https://github.com/sezuan/core
PHP | 1080 lines | 655 code | 71 blank | 354 comment | 130 complexity | e3836460d9f77b0fe045ebb11e75c80b MD5 | raw file
   1<?php
   2/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
   3
   4/**
   5 * Pure-PHP implementation of Triple DES.
   6 *
   7 * Uses mcrypt, if available, and an internal implementation, otherwise.  Operates in the EDE3 mode (encrypt-decrypt-encrypt).
   8 *
   9 * PHP versions 4 and 5
  10 *
  11 * Here's a short example of how to use this library:
  12 * <code>
  13 * <?php
  14 *    include('Crypt/TripleDES.php');
  15 *
  16 *    $des = new Crypt_TripleDES();
  17 *
  18 *    $des->setKey('abcdefghijklmnopqrstuvwx');
  19 *
  20 *    $size = 10 * 1024;
  21 *    $plaintext = '';
  22 *    for ($i = 0; $i < $size; $i++) {
  23 *        $plaintext.= 'a';
  24 *    }
  25 *
  26 *    echo $des->decrypt($des->encrypt($plaintext));
  27 * ?>
  28 * </code>
  29 *
  30 * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  31 * of this software and associated documentation files (the "Software"), to deal
  32 * in the Software without restriction, including without limitation the rights
  33 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  34 * copies of the Software, and to permit persons to whom the Software is
  35 * furnished to do so, subject to the following conditions:
  36 * 
  37 * The above copyright notice and this permission notice shall be included in
  38 * all copies or substantial portions of the Software.
  39 * 
  40 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  42 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  43 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  44 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  45 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  46 * THE SOFTWARE.
  47 *
  48 * @category   Crypt
  49 * @package    Crypt_TripleDES
  50 * @author     Jim Wigginton <terrafrost@php.net>
  51 * @copyright  MMVII Jim Wigginton
  52 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
  53 * @version    $Id: TripleDES.php,v 1.13 2010/02/26 03:40:25 terrafrost Exp $
  54 * @link       http://phpseclib.sourceforge.net
  55 */
  56
  57/**
  58 * Include Crypt_DES
  59 */
  60if (!class_exists('Crypt_DES')) {
  61    require_once('DES.php');
  62}
  63
  64/**
  65 * Encrypt / decrypt using inner chaining
  66 *
  67 * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3).
  68 */
  69define('CRYPT_DES_MODE_3CBC', -2);
  70
  71/**
  72 * Encrypt / decrypt using outer chaining
  73 *
  74 * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC.
  75 */
  76define('CRYPT_DES_MODE_CBC3', CRYPT_DES_MODE_CBC);
  77
  78/**
  79 * Pure-PHP implementation of Triple DES.
  80 *
  81 * @author  Jim Wigginton <terrafrost@php.net>
  82 * @version 0.1.0
  83 * @access  public
  84 * @package Crypt_TerraDES
  85 */
  86class Crypt_TripleDES {
  87    /**
  88     * The Three Keys
  89     *
  90     * @see Crypt_TripleDES::setKey()
  91     * @var String
  92     * @access private
  93     */
  94    var $key = "\0\0\0\0\0\0\0\0";
  95
  96    /**
  97     * The Encryption Mode
  98     *
  99     * @see Crypt_TripleDES::Crypt_TripleDES()
 100     * @var Integer
 101     * @access private
 102     */
 103    var $mode = CRYPT_DES_MODE_CBC;
 104
 105    /**
 106     * Continuous Buffer status
 107     *
 108     * @see Crypt_TripleDES::enableContinuousBuffer()
 109     * @var Boolean
 110     * @access private
 111     */
 112    var $continuousBuffer = false;
 113
 114    /**
 115     * Padding status
 116     *
 117     * @see Crypt_TripleDES::enablePadding()
 118     * @var Boolean
 119     * @access private
 120     */
 121    var $padding = true;
 122
 123    /**
 124     * The Initialization Vector
 125     *
 126     * @see Crypt_TripleDES::setIV()
 127     * @var String
 128     * @access private
 129     */
 130    var $iv = "\0\0\0\0\0\0\0\0";
 131
 132    /**
 133     * A "sliding" Initialization Vector
 134     *
 135     * @see Crypt_TripleDES::enableContinuousBuffer()
 136     * @var String
 137     * @access private
 138     */
 139    var $encryptIV = "\0\0\0\0\0\0\0\0";
 140
 141    /**
 142     * A "sliding" Initialization Vector
 143     *
 144     * @see Crypt_TripleDES::enableContinuousBuffer()
 145     * @var String
 146     * @access private
 147     */
 148    var $decryptIV = "\0\0\0\0\0\0\0\0";
 149
 150    /**
 151     * The Crypt_DES objects
 152     *
 153     * @var Array
 154     * @access private
 155     */
 156    var $des;
 157
 158    /**
 159     * mcrypt resource for encryption
 160     *
 161     * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
 162     * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
 163     *
 164     * @see Crypt_TripleDES::encrypt()
 165     * @var String
 166     * @access private
 167     */
 168    var $enmcrypt;
 169
 170    /**
 171     * mcrypt resource for decryption
 172     *
 173     * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
 174     * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
 175     *
 176     * @see Crypt_TripleDES::decrypt()
 177     * @var String
 178     * @access private
 179     */
 180    var $demcrypt;
 181
 182    /**
 183     * Does the enmcrypt resource need to be (re)initialized?
 184     *
 185     * @see Crypt_TripleDES::setKey()
 186     * @see Crypt_TripleDES::setIV()
 187     * @var Boolean
 188     * @access private
 189     */
 190    var $enchanged = true;
 191
 192    /**
 193     * Does the demcrypt resource need to be (re)initialized?
 194     *
 195     * @see Crypt_TripleDES::setKey()
 196     * @see Crypt_TripleDES::setIV()
 197     * @var Boolean
 198     * @access private
 199     */
 200    var $dechanged = true;
 201
 202    /**
 203     * Is the mode one that is paddable?
 204     *
 205     * @see Crypt_TripleDES::Crypt_TripleDES()
 206     * @var Boolean
 207     * @access private
 208     */
 209    var $paddable = false;
 210
 211    /**
 212     * Encryption buffer for CTR, OFB and CFB modes
 213     *
 214     * @see Crypt_TripleDES::encrypt()
 215     * @var Array
 216     * @access private
 217     */
 218    var $enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
 219
 220    /**
 221     * Decryption buffer for CTR, OFB and CFB modes
 222     *
 223     * @see Crypt_TripleDES::decrypt()
 224     * @var Array
 225     * @access private
 226     */
 227    var $debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
 228
 229    /**
 230     * mcrypt resource for CFB mode
 231     *
 232     * @see Crypt_TripleDES::encrypt()
 233     * @see Crypt_TripleDES::decrypt()
 234     * @var String
 235     * @access private
 236     */
 237    var $ecb;
 238
 239    /**
 240     * Default Constructor.
 241     *
 242     * Determines whether or not the mcrypt extension should be used.  $mode should only, at present, be
 243     * CRYPT_DES_MODE_ECB or CRYPT_DES_MODE_CBC.  If not explictly set, CRYPT_DES_MODE_CBC will be used.
 244     *
 245     * @param optional Integer $mode
 246     * @return Crypt_TripleDES
 247     * @access public
 248     */
 249    function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC)
 250    {
 251        if ( !defined('CRYPT_DES_MODE') ) {
 252            switch (true) {
 253                case extension_loaded('mcrypt') && in_array('tripledes', mcrypt_list_algorithms()):
 254                    define('CRYPT_DES_MODE', CRYPT_DES_MODE_MCRYPT);
 255                    break;
 256                default:
 257                    define('CRYPT_DES_MODE', CRYPT_DES_MODE_INTERNAL);
 258            }
 259        }
 260
 261        if ( $mode == CRYPT_DES_MODE_3CBC ) {
 262            $this->mode = CRYPT_DES_MODE_3CBC;
 263            $this->des = array(
 264                new Crypt_DES(CRYPT_DES_MODE_CBC),
 265                new Crypt_DES(CRYPT_DES_MODE_CBC),
 266                new Crypt_DES(CRYPT_DES_MODE_CBC)
 267            );
 268            $this->paddable = true;
 269
 270            // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
 271            $this->des[0]->disablePadding();
 272            $this->des[1]->disablePadding();
 273            $this->des[2]->disablePadding();
 274
 275            return;
 276        }
 277
 278        switch ( CRYPT_DES_MODE ) {
 279            case CRYPT_DES_MODE_MCRYPT:
 280                switch ($mode) {
 281                    case CRYPT_DES_MODE_ECB:
 282                        $this->paddable = true;
 283                        $this->mode = MCRYPT_MODE_ECB;
 284                        break;
 285                    case CRYPT_DES_MODE_CTR:
 286                        $this->mode = 'ctr';
 287                        break;
 288                    case CRYPT_DES_MODE_CFB:
 289                        $this->mode = 'ncfb';
 290                        $this->ecb = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
 291                        break;
 292                    case CRYPT_DES_MODE_OFB:
 293                        $this->mode = MCRYPT_MODE_NOFB;
 294                        break;
 295                    case CRYPT_DES_MODE_CBC:
 296                    default:
 297                        $this->paddable = true;
 298                        $this->mode = MCRYPT_MODE_CBC;
 299                }
 300                $this->enmcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
 301                $this->demcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
 302
 303                break;
 304            default:
 305                $this->des = array(
 306                    new Crypt_DES(CRYPT_DES_MODE_ECB),
 307                    new Crypt_DES(CRYPT_DES_MODE_ECB),
 308                    new Crypt_DES(CRYPT_DES_MODE_ECB)
 309                );
 310 
 311                // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
 312                $this->des[0]->disablePadding();
 313                $this->des[1]->disablePadding();
 314                $this->des[2]->disablePadding();
 315
 316                switch ($mode) {
 317                    case CRYPT_DES_MODE_ECB:
 318                    case CRYPT_DES_MODE_CBC:
 319                        $this->paddable = true;
 320                        $this->mode = $mode;
 321                        break;
 322                    case CRYPT_DES_MODE_CTR:
 323                    case CRYPT_DES_MODE_CFB:
 324                    case CRYPT_DES_MODE_OFB:
 325                        $this->mode = $mode;
 326                        break;
 327                    default:
 328                        $this->paddable = true;
 329                        $this->mode = CRYPT_DES_MODE_CBC;
 330                }
 331        }
 332    }
 333
 334    /**
 335     * Sets the key.
 336     *
 337     * Keys can be of any length.  Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
 338     * 192-bit (eg. strlen($key) == 24) keys.  This function pads and truncates $key as appropriate.
 339     *
 340     * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
 341     *
 342     * If the key is not explicitly set, it'll be assumed to be all zero's.
 343     *
 344     * @access public
 345     * @param String $key
 346     */
 347    function setKey($key)
 348    {
 349        $length = strlen($key);
 350        if ($length > 8) {
 351            $key = str_pad($key, 24, chr(0));
 352            // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
 353            // http://php.net/function.mcrypt-encrypt#47973
 354            //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
 355        } else {
 356            $key = str_pad($key, 8, chr(0));
 357        }
 358        $this->key = $key;
 359        switch (true) {
 360            case CRYPT_DES_MODE == CRYPT_DES_MODE_INTERNAL:
 361            case $this->mode == CRYPT_DES_MODE_3CBC:
 362                $this->des[0]->setKey(substr($key,  0, 8));
 363                $this->des[1]->setKey(substr($key,  8, 8));
 364                $this->des[2]->setKey(substr($key, 16, 8));
 365        }
 366        $this->enchanged = $this->dechanged = true;
 367    }
 368
 369    /**
 370     * Sets the password.
 371     *
 372     * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
 373     *     {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
 374     *         $hash, $salt, $method
 375     *
 376     * @param String $password
 377     * @param optional String $method
 378     * @access public
 379     */
 380    function setPassword($password, $method = 'pbkdf2')
 381    {
 382        $key = '';
 383
 384        switch ($method) {
 385            default: // 'pbkdf2'
 386                list(, , $hash, $salt, $count) = func_get_args();
 387                if (!isset($hash)) {
 388                    $hash = 'sha1';
 389                }
 390                // WPA and WPA2 use the SSID as the salt
 391                if (!isset($salt)) {
 392                    $salt = 'phpseclib';
 393                }
 394                // RFC2898#section-4.2 uses 1,000 iterations by default
 395                // WPA and WPA2 use 4,096.
 396                if (!isset($count)) {
 397                    $count = 1000;
 398                }
 399
 400                if (!class_exists('Crypt_Hash')) {
 401                    require_once('Crypt/Hash.php');
 402                }
 403
 404                $i = 1;
 405                while (strlen($key) < 24) { // $dkLen == 24
 406                    $hmac = new Crypt_Hash();
 407                    $hmac->setHash($hash);
 408                    $hmac->setKey($password);
 409                    $f = $u = $hmac->hash($salt . pack('N', $i++));
 410                    for ($j = 2; $j <= $count; $j++) {
 411                        $u = $hmac->hash($u);
 412                        $f^= $u;
 413                    }
 414                    $key.= $f;
 415                }
 416        }
 417
 418        $this->setKey($key);
 419    }
 420
 421    /**
 422     * Sets the initialization vector. (optional)
 423     *
 424     * SetIV is not required when CRYPT_DES_MODE_ECB is being used.  If not explictly set, it'll be assumed
 425     * to be all zero's.
 426     *
 427     * @access public
 428     * @param String $iv
 429     */
 430    function setIV($iv)
 431    {
 432        $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, 8), 8, chr(0));
 433        if ($this->mode == CRYPT_DES_MODE_3CBC) {
 434            $this->des[0]->setIV($iv);
 435            $this->des[1]->setIV($iv);
 436            $this->des[2]->setIV($iv);
 437        }
 438        $this->enchanged = $this->dechanged = true;
 439    }
 440
 441    /**
 442     * Generate CTR XOR encryption key
 443     *
 444     * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
 445     * plaintext / ciphertext in CTR mode.
 446     *
 447     * @see Crypt_TripleDES::decrypt()
 448     * @see Crypt_TripleDES::encrypt()
 449     * @access private
 450     * @param String $iv
 451     */
 452    function _generate_xor(&$iv)
 453    {
 454        $xor = $iv;
 455        for ($j = 4; $j <= 8; $j+=4) {
 456            $temp = substr($iv, -$j, 4);
 457            switch ($temp) {
 458                case "\xFF\xFF\xFF\xFF":
 459                    $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
 460                    break;
 461                case "\x7F\xFF\xFF\xFF":
 462                    $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
 463                    break 2;
 464                default:
 465                    extract(unpack('Ncount', $temp));
 466                    $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
 467                    break 2;
 468            }
 469        }
 470
 471        return $xor;
 472    }
 473
 474    /**
 475     * Encrypts a message.
 476     *
 477     * @access public
 478     * @param String $plaintext
 479     */
 480    function encrypt($plaintext)
 481    {
 482        if ($this->paddable) {
 483            $plaintext = $this->_pad($plaintext);
 484        }
 485
 486        // if the key is smaller then 8, do what we'd normally do
 487        if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
 488            $ciphertext = $this->des[2]->encrypt($this->des[1]->decrypt($this->des[0]->encrypt($plaintext)));
 489
 490            return $ciphertext;
 491        }
 492
 493        if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
 494            if ($this->enchanged) {
 495                mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
 496                if ($this->mode == 'ncfb') {
 497                    mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
 498                }
 499                $this->enchanged = false;
 500            }
 501
 502            if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
 503                $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
 504            } else {
 505                $iv = &$this->encryptIV;
 506                $pos = &$this->enbuffer['pos'];
 507                $len = strlen($plaintext);
 508                $ciphertext = '';
 509                $i = 0;
 510                if ($pos) {
 511                    $orig_pos = $pos;
 512                    $max = 8 - $pos;
 513                    if ($len >= $max) {
 514                        $i = $max;
 515                        $len-= $max;
 516                        $pos = 0;
 517                    } else {
 518                        $i = $len;
 519                        $pos+= $len;
 520                        $len = 0;
 521                    }
 522                    $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
 523                    $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
 524                    $this->enbuffer['enmcrypt_init'] = true;
 525                }
 526                if ($len >= 8) {
 527                    if ($this->enbuffer['enmcrypt_init'] === false || $len > 950) {
 528                        if ($this->enbuffer['enmcrypt_init'] === true) {
 529                            mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
 530                            $this->enbuffer['enmcrypt_init'] = false;
 531                        }
 532                        $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % 8));
 533                        $iv = substr($ciphertext, -8);
 534                        $i = strlen($ciphertext);
 535                        $len%= 8;
 536                    } else {
 537                        while ($len >= 8) {
 538                            $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, 8);
 539                            $ciphertext.= $iv;
 540                            $len-= 8;
 541                            $i+= 8;
 542                        }
 543                    }
 544                } 
 545                if ($len) {
 546                    $iv = mcrypt_generic($this->ecb, $iv);
 547                    $block = $iv ^ substr($plaintext, $i);
 548                    $iv = substr_replace($iv, $block, 0, $len);
 549                    $ciphertext.= $block;
 550                    $pos = $len;
 551                }
 552                return $ciphertext;
 553            }
 554
 555            if (!$this->continuousBuffer) {
 556                mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
 557            }
 558
 559            return $ciphertext;
 560        }
 561
 562        if (strlen($this->key) <= 8) {
 563            $this->des[0]->mode = $this->mode;
 564
 565            return $this->des[0]->encrypt($plaintext);
 566        }
 567
 568        $des = $this->des;
 569
 570        $buffer = &$this->enbuffer;
 571        $continuousBuffer = $this->continuousBuffer;
 572        $ciphertext = '';
 573        switch ($this->mode) {
 574            case CRYPT_DES_MODE_ECB:
 575                for ($i = 0; $i < strlen($plaintext); $i+=8) {
 576                    $block = substr($plaintext, $i, 8);
 577                    // all of these _processBlock calls could, in theory, be put in a function - say Crypt_TripleDES::_ede_encrypt() or something.
 578                    // only problem with that: it would slow encryption and decryption down.  $this->des would have to be called every time that
 579                    // function is called, instead of once for the whole string of text that's being encrypted, which would, in turn, make 
 580                    // encryption and decryption take more time, per this:
 581                    //
 582                    // http://blog.libssh2.org/index.php?/archives/21-Compiled-Variables.html
 583                    $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
 584                    $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
 585                    $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
 586                    $ciphertext.= $block;
 587                }
 588                break;
 589            case CRYPT_DES_MODE_CBC:
 590                $xor = $this->encryptIV;
 591                for ($i = 0; $i < strlen($plaintext); $i+=8) {
 592                    $block = substr($plaintext, $i, 8) ^ $xor;
 593                    $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
 594                    $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
 595                    $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
 596                    $xor = $block;
 597                    $ciphertext.= $block;
 598                }
 599                if ($this->continuousBuffer) {
 600                    $this->encryptIV = $xor;
 601                }
 602                break;
 603            case CRYPT_DES_MODE_CTR:
 604                $xor = $this->encryptIV;
 605                if (strlen($buffer['encrypted'])) {
 606                    for ($i = 0; $i < strlen($plaintext); $i+=8) {
 607                        $block = substr($plaintext, $i, 8);
 608                        $key = $this->_generate_xor($xor);
 609                        $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
 610                        $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
 611                        $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
 612                        $buffer['encrypted'].= $key;
 613                        $key = $this->_string_shift($buffer['encrypted'], 8);
 614                        $ciphertext.= $block ^ $key;
 615                    }
 616                } else {
 617                    for ($i = 0; $i < strlen($plaintext); $i+=8) {
 618                        $block = substr($plaintext, $i, 8);
 619                        $key = $this->_generate_xor($xor);
 620                        $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
 621                        $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
 622                        $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
 623                        $ciphertext.= $block ^ $key;
 624                    }
 625                }
 626                if ($this->continuousBuffer) {
 627                    $this->encryptIV = $xor;
 628                    if ($start = strlen($plaintext) & 7) {
 629                        $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
 630                    }
 631                }
 632                break;
 633            case CRYPT_DES_MODE_CFB:
 634                if (strlen($buffer['xor'])) {
 635                    $ciphertext = $plaintext ^ $buffer['xor'];
 636                    $iv = $buffer['encrypted'] . $ciphertext;
 637                    $start = strlen($ciphertext);
 638                    $buffer['encrypted'].= $ciphertext;
 639                    $buffer['xor'] = substr($buffer['xor'], strlen($ciphertext));
 640                } else {
 641                    $ciphertext = '';
 642                    $iv = $this->encryptIV;
 643                    $start = 0;
 644                }
 645
 646                for ($i = $start; $i < strlen($plaintext); $i+=8) {
 647                    $block = substr($plaintext, $i, 8);
 648                    $iv = $des[0]->_processBlock($iv, CRYPT_DES_ENCRYPT);
 649                    $iv = $des[1]->_processBlock($iv, CRYPT_DES_DECRYPT);
 650                    $xor= $des[2]->_processBlock($iv, CRYPT_DES_ENCRYPT);
 651
 652                    $iv = $block ^ $xor;
 653                    if ($continuousBuffer && strlen($iv) != 8) {
 654                        $buffer = array(
 655                            'encrypted' => $iv,
 656                            'xor' => substr($xor, strlen($iv))
 657                        );
 658                    }
 659                    $ciphertext.= $iv;
 660                }
 661
 662                if ($this->continuousBuffer) {
 663                    $this->encryptIV = $iv;
 664                }
 665                break;
 666            case CRYPT_DES_MODE_OFB:
 667                $xor = $this->encryptIV;
 668                if (strlen($buffer['xor'])) {
 669                    for ($i = 0; $i < strlen($plaintext); $i+=8) {
 670                        $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 671                        $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
 672                        $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 673                        $buffer['xor'].= $xor;
 674                        $key = $this->_string_shift($buffer['xor'], 8);
 675                        $ciphertext.= substr($plaintext, $i, 8) ^ $key;
 676                    }
 677                } else {
 678                    for ($i = 0; $i < strlen($plaintext); $i+=8) {
 679                        $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 680                        $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
 681                        $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 682                        $ciphertext.= substr($plaintext, $i, 8) ^ $xor;
 683                    }
 684                    $key = $xor;
 685                }
 686                if ($this->continuousBuffer) {
 687                    $this->encryptIV = $xor;
 688                    if ($start = strlen($plaintext) & 7) {
 689                         $buffer['xor'] = substr($key, $start) . $buffer['xor'];
 690                    }
 691                }
 692        }
 693
 694        return $ciphertext;
 695    }
 696
 697    /**
 698     * Decrypts a message.
 699     *
 700     * @access public
 701     * @param String $ciphertext
 702     */
 703    function decrypt($ciphertext)
 704    {
 705        if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
 706            $plaintext = $this->des[0]->decrypt($this->des[1]->encrypt($this->des[2]->decrypt($ciphertext)));
 707
 708            return $this->_unpad($plaintext);
 709        }
 710
 711        if ($this->paddable) {
 712            // we pad with chr(0) since that's what mcrypt_generic does.  to quote from http://php.net/function.mcrypt-generic :
 713            // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
 714            $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, chr(0));
 715        }
 716
 717        if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
 718            if ($this->dechanged) {
 719                mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
 720                if ($this->mode == 'ncfb') {
 721                    mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
 722                }
 723                $this->dechanged = false;
 724            }
 725
 726            if ($this->mode != 'ncfb' || !$this->continuousBuffer) {
 727                $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
 728            } else {
 729                $iv = &$this->decryptIV;
 730                $pos = &$this->debuffer['pos'];
 731                $len = strlen($ciphertext);
 732                $plaintext = '';
 733                $i = 0;
 734                if ($pos) {
 735                    $orig_pos = $pos;
 736                    $max = 8 - $pos;
 737                    if ($len >= $max) {
 738                        $i = $max;
 739                        $len-= $max;
 740                        $pos = 0;
 741                    } else {
 742                        $i = $len;
 743                        $pos+= $len;
 744                        $len = 0;
 745                    }
 746                    $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
 747                    $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
 748                }
 749                if ($len >= 8) {
 750                    $cb = substr($ciphertext, $i, $len - $len % 8);
 751                    $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
 752                    $iv = substr($cb, -8);
 753                    $len%= 8;
 754                }
 755                if ($len) {
 756                    $iv = mcrypt_generic($this->ecb, $iv);
 757                    $cb = substr($ciphertext, -$len);
 758                    $plaintext.= $iv ^ $cb;
 759                    $iv = substr_replace($iv, $cb, 0, $len);
 760                    $pos = $len;
 761                }
 762                return $plaintext;
 763            }
 764
 765            if (!$this->continuousBuffer) {
 766                mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
 767            }
 768
 769            return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
 770        }
 771
 772        if (strlen($this->key) <= 8) {
 773            $this->des[0]->mode = $this->mode;
 774            $plaintext = $this->des[0]->decrypt($ciphertext);
 775            return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
 776        }
 777
 778        $des = $this->des;
 779
 780        $buffer = &$this->debuffer;
 781        $continuousBuffer = $this->continuousBuffer;
 782        $plaintext = '';
 783        switch ($this->mode) {
 784            case CRYPT_DES_MODE_ECB:
 785                for ($i = 0; $i < strlen($ciphertext); $i+=8) {
 786                    $block = substr($ciphertext, $i, 8);
 787                    $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
 788                    $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
 789                    $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
 790                    $plaintext.= $block;
 791                }
 792                break;
 793            case CRYPT_DES_MODE_CBC:
 794                $xor = $this->decryptIV;
 795                for ($i = 0; $i < strlen($ciphertext); $i+=8) {
 796                    $orig = $block = substr($ciphertext, $i, 8);
 797                    $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
 798                    $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
 799                    $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
 800                    $plaintext.= $block ^ $xor;
 801                    $xor = $orig;
 802                }
 803                if ($this->continuousBuffer) {
 804                    $this->decryptIV = $xor;
 805                }
 806                break;
 807            case CRYPT_DES_MODE_CTR:
 808                $xor = $this->decryptIV;
 809                if (strlen($buffer['ciphertext'])) {
 810                    for ($i = 0; $i < strlen($ciphertext); $i+=8) {
 811                        $block = substr($ciphertext, $i, 8);
 812                        $key = $this->_generate_xor($xor);
 813                        $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
 814                        $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
 815                        $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
 816                        $buffer['ciphertext'].= $key;
 817                        $key = $this->_string_shift($buffer['ciphertext'], 8);
 818                        $plaintext.= $block ^ $key;
 819                    }
 820                } else {
 821                    for ($i = 0; $i < strlen($ciphertext); $i+=8) {
 822                        $block = substr($ciphertext, $i, 8);
 823                        $key = $this->_generate_xor($xor);
 824                        $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
 825                        $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
 826                        $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
 827                        $plaintext.= $block ^ $key;
 828                    }
 829                }
 830                if ($this->continuousBuffer) {
 831                    $this->decryptIV = $xor;
 832                    if ($start = strlen($plaintext) & 7) {
 833                        $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
 834                    }
 835                }
 836                break;
 837            case CRYPT_DES_MODE_CFB:
 838                if (strlen($buffer['ciphertext'])) {
 839                    $plaintext = $ciphertext ^ substr($this->decryptIV, strlen($buffer['ciphertext']));
 840                    $buffer['ciphertext'].= substr($ciphertext, 0, strlen($plaintext));
 841                    if (strlen($buffer['ciphertext']) != 8) {
 842                        $block = $this->decryptIV;
 843                    } else {
 844                        $block = $buffer['ciphertext'];
 845                        $xor = $des[0]->_processBlock($buffer['ciphertext'], CRYPT_DES_ENCRYPT);
 846                        $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
 847                        $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 848                        $buffer['ciphertext'] = '';
 849                    }
 850                    $start = strlen($plaintext);
 851                } else {
 852                    $plaintext = '';
 853                    $xor = $des[0]->_processBlock($this->decryptIV, CRYPT_DES_ENCRYPT);
 854                    $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
 855                    $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 856                    $start = 0;
 857                }
 858
 859                for ($i = $start; $i < strlen($ciphertext); $i+=8) {
 860                    $block = substr($ciphertext, $i, 8);
 861                    $plaintext.= $block ^ $xor;
 862                    if ($continuousBuffer && strlen($block) != 8) {
 863                        $buffer['ciphertext'].= $block;
 864                        $block = $xor;
 865                    } else if (strlen($block) == 8) {
 866                        $xor = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
 867                        $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
 868                        $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 869                    }
 870                }
 871                if ($this->continuousBuffer) {
 872                    $this->decryptIV = $block;
 873                }
 874                break;
 875            case CRYPT_DES_MODE_OFB:
 876                $xor = $this->decryptIV;
 877                if (strlen($buffer['xor'])) {
 878                    for ($i = 0; $i < strlen($ciphertext); $i+=8) {
 879                        $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 880                        $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
 881                        $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 882                        $buffer['xor'].= $xor;
 883                        $key = $this->_string_shift($buffer['xor'], 8);
 884                        $plaintext.= substr($ciphertext, $i, 8) ^ $key;
 885                    }
 886                } else {
 887                    for ($i = 0; $i < strlen($ciphertext); $i+=8) {
 888                        $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 889                        $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
 890                        $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
 891                        $plaintext.= substr($ciphertext, $i, 8) ^ $xor;
 892                    }
 893                    $key = $xor;
 894                }
 895                if ($this->continuousBuffer) {
 896                    $this->decryptIV = $xor;
 897                    if ($start = strlen($ciphertext) & 7) {
 898                         $buffer['xor'] = substr($key, $start) . $buffer['xor'];
 899                    }
 900                }
 901        }
 902
 903        return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
 904    }
 905
 906    /**
 907     * Treat consecutive "packets" as if they are a continuous buffer.
 908     *
 909     * Say you have a 16-byte plaintext $plaintext.  Using the default behavior, the two following code snippets
 910     * will yield different outputs:
 911     *
 912     * <code>
 913     *    echo $des->encrypt(substr($plaintext, 0, 8));
 914     *    echo $des->encrypt(substr($plaintext, 8, 8));
 915     * </code>
 916     * <code>
 917     *    echo $des->encrypt($plaintext);
 918     * </code>
 919     *
 920     * The solution is to enable the continuous buffer.  Although this will resolve the above discrepancy, it creates
 921     * another, as demonstrated with the following:
 922     *
 923     * <code>
 924     *    $des->encrypt(substr($plaintext, 0, 8));
 925     *    echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
 926     * </code>
 927     * <code>
 928     *    echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
 929     * </code>
 930     *
 931     * With the continuous buffer disabled, these would yield the same output.  With it enabled, they yield different
 932     * outputs.  The reason is due to the fact that the initialization vector's change after every encryption /
 933     * decryption round when the continuous buffer is enabled.  When it's disabled, they remain constant.
 934     *
 935     * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
 936     * encryption / decryption round, whereas otherwise, it'd remain constant.  For this reason, it's recommended that
 937     * continuous buffers not be used.  They do offer better security and are, in fact, sometimes required (SSH uses them),
 938     * however, they are also less intuitive and more likely to cause you problems.
 939     *
 940     * @see Crypt_TripleDES::disableContinuousBuffer()
 941     * @access public
 942     */
 943    function enableContinuousBuffer()
 944    {
 945        $this->continuousBuffer = true;
 946        if ($this->mode == CRYPT_DES_MODE_3CBC) {
 947            $this->des[0]->enableContinuousBuffer();
 948            $this->des[1]->enableContinuousBuffer();
 949            $this->des[2]->enableContinuousBuffer();
 950        }
 951    }
 952
 953    /**
 954     * Treat consecutive packets as if they are a discontinuous buffer.
 955     *
 956     * The default behavior.
 957     *
 958     * @see Crypt_TripleDES::enableContinuousBuffer()
 959     * @access public
 960     */
 961    function disableContinuousBuffer()
 962    {
 963        $this->continuousBuffer = false;
 964        $this->encryptIV = $this->iv;
 965        $this->decryptIV = $this->iv;
 966        $this->enchanged = true;
 967        $this->dechanged = true;
 968        $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
 969        $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
 970
 971        if ($this->mode == CRYPT_DES_MODE_3CBC) {
 972            $this->des[0]->disableContinuousBuffer();
 973            $this->des[1]->disableContinuousBuffer();
 974            $this->des[2]->disableContinuousBuffer();
 975        }
 976    }
 977
 978    /**
 979     * Pad "packets".
 980     *
 981     * DES works by encrypting eight bytes at a time.  If you ever need to encrypt or decrypt something that's not
 982     * a multiple of eight, it becomes necessary to pad the input so that it's length is a multiple of eight.
 983     *
 984     * Padding is enabled by default.  Sometimes, however, it is undesirable to pad strings.  Such is the case in SSH1,
 985     * where "packets" are padded with random bytes before being encrypted.  Unpad these packets and you risk stripping
 986     * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
 987     * transmitted separately)
 988     *
 989     * @see Crypt_TripleDES::disablePadding()
 990     * @access public
 991     */
 992    function enablePadding()
 993    {
 994        $this->padding = true;
 995    }
 996
 997    /**
 998     * Do not pad packets.
 999     *
1000     * @see Crypt_TripleDES::enablePadding()
1001     * @access public
1002     */
1003    function disablePadding()
1004    {
1005        $this->padding = false;
1006    }
1007
1008    /**
1009     * Pads a string
1010     *
1011     * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize (8).
1012     * 8 - (strlen($text) & 7) bytes are added, each of which is equal to chr(8 - (strlen($text) & 7)
1013     *
1014     * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
1015     * and padding will, hence forth, be enabled.
1016     *
1017     * @see Crypt_TripleDES::_unpad()
1018     * @access private
1019     */
1020    function _pad($text)
1021    {
1022        $length = strlen($text);
1023
1024        if (!$this->padding) {
1025            if (($length & 7) == 0) {
1026                return $text;
1027            } else {
1028                user_error("The plaintext's length ($length) is not a multiple of the block size (8)", E_USER_NOTICE);
1029                $this->padding = true;
1030            }
1031        }
1032
1033        $pad = 8 - ($length & 7);
1034        return str_pad($text, $length + $pad, chr($pad));
1035    }
1036
1037    /**
1038     * Unpads a string
1039     *
1040     * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
1041     * and false will be returned.
1042     *
1043     * @see Crypt_TripleDES::_pad()
1044     * @access private
1045     */
1046    function _unpad($text)
1047    {
1048        if (!$this->padding) {
1049            return $text;
1050        }
1051
1052        $length = ord($text[strlen($text) - 1]);
1053
1054        if (!$length || $length > 8) {
1055            return false;
1056        }
1057
1058        return substr($text, 0, -$length);
1059    }
1060
1061    /**
1062     * String Shift
1063     *
1064     * Inspired by array_shift
1065     *
1066     * @param String $string
1067     * @param optional Integer $index
1068     * @return String
1069     * @access private
1070     */
1071    function _string_shift(&$string, $index = 1)
1072    {
1073        $substr = substr($string, 0, $index);
1074        $string = substr($string, $index);
1075        return $substr;
1076    }
1077}
1078
1079// vim: ts=4:sw=4:et:
1080// vim6: fdl=1: