PHPSECLIB 0.3.1 added to the project to support SFTP transfers of lab orders and...
[openemr.git] / library / phpseclib / Crypt / TripleDES.php
blobfaf8c18adea6721276ee77b22b12bb197d6612e9
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4 /**
5 * Pure-PHP implementation of Triple DES.
7 * Uses mcrypt, if available, and an internal implementation, otherwise. Operates in the EDE3 mode (encrypt-decrypt-encrypt).
9 * PHP versions 4 and 5
11 * Here's a short example of how to use this library:
12 * <code>
13 * <?php
14 * include('Crypt/TripleDES.php');
16 * $des = new Crypt_TripleDES();
18 * $des->setKey('abcdefghijklmnopqrstuvwx');
20 * $size = 10 * 1024;
21 * $plaintext = '';
22 * for ($i = 0; $i < $size; $i++) {
23 * $plaintext.= 'a';
24 * }
26 * echo $des->decrypt($des->encrypt($plaintext));
27 * ?>
28 * </code>
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:
37 * The above copyright notice and this permission notice shall be included in
38 * all copies or substantial portions of the Software.
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.
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
57 /**
58 * Include Crypt_DES
60 if (!class_exists('Crypt_DES')) {
61 require_once('DES.php');
64 /**
65 * Encrypt / decrypt using inner chaining
67 * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3).
69 define('CRYPT_DES_MODE_3CBC', -2);
71 /**
72 * Encrypt / decrypt using outer chaining
74 * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC.
76 define('CRYPT_DES_MODE_CBC3', CRYPT_DES_MODE_CBC);
78 /**
79 * Pure-PHP implementation of Triple DES.
81 * @author Jim Wigginton <terrafrost@php.net>
82 * @version 0.1.0
83 * @access public
84 * @package Crypt_TerraDES
86 class Crypt_TripleDES {
87 /**
88 * The Three Keys
90 * @see Crypt_TripleDES::setKey()
91 * @var String
92 * @access private
94 var $key = "\0\0\0\0\0\0\0\0";
96 /**
97 * The Encryption Mode
99 * @see Crypt_TripleDES::Crypt_TripleDES()
100 * @var Integer
101 * @access private
103 var $mode = CRYPT_DES_MODE_CBC;
106 * Continuous Buffer status
108 * @see Crypt_TripleDES::enableContinuousBuffer()
109 * @var Boolean
110 * @access private
112 var $continuousBuffer = false;
115 * Padding status
117 * @see Crypt_TripleDES::enablePadding()
118 * @var Boolean
119 * @access private
121 var $padding = true;
124 * The Initialization Vector
126 * @see Crypt_TripleDES::setIV()
127 * @var String
128 * @access private
130 var $iv = "\0\0\0\0\0\0\0\0";
133 * A "sliding" Initialization Vector
135 * @see Crypt_TripleDES::enableContinuousBuffer()
136 * @var String
137 * @access private
139 var $encryptIV = "\0\0\0\0\0\0\0\0";
142 * A "sliding" Initialization Vector
144 * @see Crypt_TripleDES::enableContinuousBuffer()
145 * @var String
146 * @access private
148 var $decryptIV = "\0\0\0\0\0\0\0\0";
151 * The Crypt_DES objects
153 * @var Array
154 * @access private
156 var $des;
159 * mcrypt resource for encryption
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.
164 * @see Crypt_TripleDES::encrypt()
165 * @var String
166 * @access private
168 var $enmcrypt;
171 * mcrypt resource for decryption
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.
176 * @see Crypt_TripleDES::decrypt()
177 * @var String
178 * @access private
180 var $demcrypt;
183 * Does the enmcrypt resource need to be (re)initialized?
185 * @see Crypt_TripleDES::setKey()
186 * @see Crypt_TripleDES::setIV()
187 * @var Boolean
188 * @access private
190 var $enchanged = true;
193 * Does the demcrypt resource need to be (re)initialized?
195 * @see Crypt_TripleDES::setKey()
196 * @see Crypt_TripleDES::setIV()
197 * @var Boolean
198 * @access private
200 var $dechanged = true;
203 * Is the mode one that is paddable?
205 * @see Crypt_TripleDES::Crypt_TripleDES()
206 * @var Boolean
207 * @access private
209 var $paddable = false;
212 * Encryption buffer for CTR, OFB and CFB modes
214 * @see Crypt_TripleDES::encrypt()
215 * @var String
216 * @access private
218 var $enbuffer = '';
221 * Decryption buffer for CTR, OFB and CFB modes
223 * @see Crypt_TripleDES::decrypt()
224 * @var String
225 * @access private
227 var $debuffer = '';
230 * mcrypt resource for CFB mode
232 * @see Crypt_TripleDES::encrypt()
233 * @see Crypt_TripleDES::decrypt()
234 * @var String
235 * @access private
237 var $ecb;
240 * Default Constructor.
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.
245 * @param optional Integer $mode
246 * @return Crypt_TripleDES
247 * @access public
249 function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC)
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);
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)
268 $this->paddable = true;
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();
275 return;
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 break;
291 case CRYPT_DES_MODE_OFB:
292 $this->mode = MCRYPT_MODE_NOFB;
293 break;
294 case CRYPT_DES_MODE_CBC:
295 default:
296 $this->paddable = true;
297 $this->mode = MCRYPT_MODE_CBC;
300 break;
301 default:
302 $this->des = array(
303 new Crypt_DES(CRYPT_DES_MODE_ECB),
304 new Crypt_DES(CRYPT_DES_MODE_ECB),
305 new Crypt_DES(CRYPT_DES_MODE_ECB)
308 // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
309 $this->des[0]->disablePadding();
310 $this->des[1]->disablePadding();
311 $this->des[2]->disablePadding();
313 switch ($mode) {
314 case CRYPT_DES_MODE_ECB:
315 case CRYPT_DES_MODE_CBC:
316 $this->paddable = true;
317 $this->mode = $mode;
318 break;
319 case CRYPT_DES_MODE_CTR:
320 case CRYPT_DES_MODE_CFB:
321 case CRYPT_DES_MODE_OFB:
322 $this->mode = $mode;
323 break;
324 default:
325 $this->paddable = true;
326 $this->mode = CRYPT_DES_MODE_CBC;
332 * Sets the key.
334 * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
335 * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate.
337 * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
339 * If the key is not explicitly set, it'll be assumed to be all zero's.
341 * @access public
342 * @param String $key
344 function setKey($key)
346 $length = strlen($key);
347 if ($length > 8) {
348 $key = str_pad($key, 24, chr(0));
349 // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
350 // http://php.net/function.mcrypt-encrypt#47973
351 //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
352 } else {
353 $key = str_pad($key, 8, chr(0));
355 $this->key = $key;
356 switch (true) {
357 case CRYPT_DES_MODE == CRYPT_DES_MODE_INTERNAL:
358 case $this->mode == CRYPT_DES_MODE_3CBC:
359 $this->des[0]->setKey(substr($key, 0, 8));
360 $this->des[1]->setKey(substr($key, 8, 8));
361 $this->des[2]->setKey(substr($key, 16, 8));
363 $this->enchanged = $this->dechanged = true;
367 * Sets the password.
369 * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
370 * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
371 * $hash, $salt, $method
373 * @param String $password
374 * @param optional String $method
375 * @access public
377 function setPassword($password, $method = 'pbkdf2')
379 $key = '';
381 switch ($method) {
382 default: // 'pbkdf2'
383 list(, , $hash, $salt, $count) = func_get_args();
384 if (!isset($hash)) {
385 $hash = 'sha1';
387 // WPA and WPA use the SSID as the salt
388 if (!isset($salt)) {
389 $salt = 'phpseclib';
391 // RFC2898#section-4.2 uses 1,000 iterations by default
392 // WPA and WPA2 use 4,096.
393 if (!isset($count)) {
394 $count = 1000;
397 if (!class_exists('Crypt_Hash')) {
398 require_once('Crypt/Hash.php');
401 $i = 1;
402 while (strlen($key) < 24) { // $dkLen == 24
403 $hmac = new Crypt_Hash();
404 $hmac->setHash($hash);
405 $hmac->setKey($password);
406 $f = $u = $hmac->hash($salt . pack('N', $i++));
407 for ($j = 2; $j <= $count; $j++) {
408 $u = $hmac->hash($u);
409 $f^= $u;
411 $key.= $f;
415 $this->setKey($key);
419 * Sets the initialization vector. (optional)
421 * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explictly set, it'll be assumed
422 * to be all zero's.
424 * @access public
425 * @param String $iv
427 function setIV($iv)
429 $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, 8), 8, chr(0));
430 if ($this->mode == CRYPT_DES_MODE_3CBC) {
431 $this->des[0]->setIV($iv);
432 $this->des[1]->setIV($iv);
433 $this->des[2]->setIV($iv);
435 $this->enchanged = $this->dechanged = true;
439 * Generate CTR XOR encryption key
441 * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
442 * plaintext / ciphertext in CTR mode.
444 * @see Crypt_TripleDES::decrypt()
445 * @see Crypt_TripleDES::encrypt()
446 * @access private
447 * @param Integer $length
448 * @param String $iv
450 function _generate_xor($length, &$iv)
452 $xor = '';
453 $num_blocks = ($length + 7) >> 3;
454 for ($i = 0; $i < $num_blocks; $i++) {
455 $xor.= $iv;
456 for ($j = 4; $j <= 8; $j+=4) {
457 $temp = substr($iv, -$j, 4);
458 switch ($temp) {
459 case "\xFF\xFF\xFF\xFF":
460 $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
461 break;
462 case "\x7F\xFF\xFF\xFF":
463 $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
464 break 2;
465 default:
466 extract(unpack('Ncount', $temp));
467 $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
468 break 2;
473 return $xor;
477 * Encrypts a message.
479 * @access public
480 * @param String $plaintext
482 function encrypt($plaintext)
484 if ($this->paddable) {
485 $plaintext = $this->_pad($plaintext);
488 // if the key is smaller then 8, do what we'd normally do
489 if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
490 $ciphertext = $this->des[2]->encrypt($this->des[1]->decrypt($this->des[0]->encrypt($plaintext)));
492 return $ciphertext;
495 if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
496 if ($this->enchanged) {
497 if (!isset($this->enmcrypt)) {
498 $this->enmcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
500 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
501 if ($this->mode != 'ncfb') {
502 $this->enchanged = false;
506 if ($this->mode != 'ncfb') {
507 $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
508 } else {
509 if ($this->enchanged) {
510 $this->ecb = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
511 mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
512 $this->enchanged = false;
515 if (strlen($this->enbuffer)) {
516 $ciphertext = $plaintext ^ substr($this->encryptIV, strlen($this->enbuffer));
517 $this->enbuffer.= $ciphertext;
518 if (strlen($this->enbuffer) == 8) {
519 $this->encryptIV = $this->enbuffer;
520 $this->enbuffer = '';
521 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
523 $plaintext = substr($plaintext, strlen($ciphertext));
524 } else {
525 $ciphertext = '';
528 $last_pos = strlen($plaintext) & 0xFFFFFFF8;
529 $ciphertext.= $last_pos ? mcrypt_generic($this->enmcrypt, substr($plaintext, 0, $last_pos)) : '';
531 if (strlen($plaintext) & 0x7) {
532 if (strlen($ciphertext)) {
533 $this->encryptIV = substr($ciphertext, -8);
535 $this->encryptIV = mcrypt_generic($this->ecb, $this->encryptIV);
536 $this->enbuffer = substr($plaintext, $last_pos) ^ $this->encryptIV;
537 $ciphertext.= $this->enbuffer;
541 if (!$this->continuousBuffer) {
542 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
545 return $ciphertext;
548 if (strlen($this->key) <= 8) {
549 $this->des[0]->mode = $this->mode;
551 return $this->des[0]->encrypt($plaintext);
554 $des = $this->des;
556 $buffer = &$this->enbuffer;
557 $continuousBuffer = $this->continuousBuffer;
558 $ciphertext = '';
559 switch ($this->mode) {
560 case CRYPT_DES_MODE_ECB:
561 for ($i = 0; $i < strlen($plaintext); $i+=8) {
562 $block = substr($plaintext, $i, 8);
563 // all of these _processBlock calls could, in theory, be put in a function - say Crypt_TripleDES::_ede_encrypt() or something.
564 // only problem with that: it would slow encryption and decryption down. $this->des would have to be called every time that
565 // function is called, instead of once for the whole string of text that's being encrypted, which would, in turn, make
566 // encryption and decryption take more time, per this:
568 // http://blog.libssh2.org/index.php?/archives/21-Compiled-Variables.html
569 $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
570 $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
571 $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
572 $ciphertext.= $block;
574 break;
575 case CRYPT_DES_MODE_CBC:
576 $xor = $this->encryptIV;
577 for ($i = 0; $i < strlen($plaintext); $i+=8) {
578 $block = substr($plaintext, $i, 8) ^ $xor;
579 $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
580 $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
581 $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
582 $xor = $block;
583 $ciphertext.= $block;
585 if ($this->continuousBuffer) {
586 $this->encryptIV = $xor;
588 break;
589 case CRYPT_DES_MODE_CTR:
590 $xor = $this->encryptIV;
591 if (strlen($buffer['encrypted'])) {
592 for ($i = 0; $i < strlen($plaintext); $i+=8) {
593 $block = substr($plaintext, $i, 8);
594 $key = $this->_generate_xor(8, $xor);
595 $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
596 $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
597 $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
598 $buffer['encrypted'].= $key;
599 $key = $this->_string_shift($buffer['encrypted'], 8);
600 $ciphertext.= $block ^ $key;
602 } else {
603 for ($i = 0; $i < strlen($plaintext); $i+=8) {
604 $block = substr($plaintext, $i, 8);
605 $key = $this->_generate_xor(8, $xor);
606 $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
607 $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
608 $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
609 $ciphertext.= $block ^ $key;
612 if ($this->continuousBuffer) {
613 $this->encryptIV = $xor;
614 if ($start = strlen($plaintext) & 7) {
615 $buffer['encrypted'] = substr($key, $start) . $buffer;
618 break;
619 case CRYPT_DES_MODE_CFB:
620 if (!empty($buffer['xor'])) {
621 $ciphertext = $plaintext ^ $buffer['xor'];
622 $iv = $buffer['encrypted'] . $ciphertext;
623 $start = strlen($ciphertext);
624 $buffer['encrypted'].= $ciphertext;
625 $buffer['xor'] = substr($buffer['xor'], strlen($ciphertext));
626 } else {
627 $ciphertext = '';
628 $iv = $this->encryptIV;
629 $start = 0;
632 for ($i = $start; $i < strlen($plaintext); $i+=8) {
633 $block = substr($plaintext, $i, 8);
634 $iv = $des[0]->_processBlock($iv, CRYPT_DES_ENCRYPT);
635 $iv = $des[1]->_processBlock($iv, CRYPT_DES_DECRYPT);
636 $xor= $des[2]->_processBlock($iv, CRYPT_DES_ENCRYPT);
638 $iv = $block ^ $xor;
639 if ($continuousBuffer && strlen($iv) != 8) {
640 $buffer = array(
641 'encrypted' => $iv,
642 'xor' => substr($xor, strlen($iv))
645 $ciphertext.= $iv;
648 if ($this->continuousBuffer) {
649 $this->encryptIV = $iv;
651 break;
652 case CRYPT_DES_MODE_OFB:
653 $xor = $this->encryptIV;
654 if (strlen($buffer)) {
655 for ($i = 0; $i < strlen($plaintext); $i+=8) {
656 $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
657 $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
658 $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
659 $buffer.= $xor;
660 $key = $this->_string_shift($buffer, 8);
661 $ciphertext.= substr($plaintext, $i, 8) ^ $key;
663 } else {
664 for ($i = 0; $i < strlen($plaintext); $i+=8) {
665 $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
666 $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
667 $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
668 $ciphertext.= substr($plaintext, $i, 8) ^ $xor;
670 $key = $xor;
672 if ($this->continuousBuffer) {
673 $this->encryptIV = $xor;
674 if ($start = strlen($plaintext) & 7) {
675 $buffer = substr($key, $start) . $buffer;
680 return $ciphertext;
684 * Decrypts a message.
686 * @access public
687 * @param String $ciphertext
689 function decrypt($ciphertext)
691 if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
692 $plaintext = $this->des[0]->decrypt($this->des[1]->encrypt($this->des[2]->decrypt($ciphertext)));
694 return $this->_unpad($plaintext);
697 if ($this->paddable) {
698 // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
699 // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
700 $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, chr(0));
703 if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
704 if ($this->dechanged) {
705 if (!isset($this->demcrypt)) {
706 $this->demcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
708 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
709 if ($this->mode != 'ncfb') {
710 $this->dechanged = false;
714 if ($this->mode != 'ncfb') {
715 $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
716 } else {
717 if ($this->dechanged) {
718 $this->ecb = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
719 mcrypt_generic_init($this->ecb, $this->key, "\0\0\0\0\0\0\0\0");
720 $this->dechanged = false;
723 if (strlen($this->debuffer)) {
724 $plaintext = $ciphertext ^ substr($this->decryptIV, strlen($this->debuffer));
726 $this->debuffer.= substr($ciphertext, 0, strlen($plaintext));
727 if (strlen($this->debuffer) == 8) {
728 $this->decryptIV = $this->debuffer;
729 $this->debuffer = '';
730 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
732 $ciphertext = substr($ciphertext, strlen($plaintext));
733 } else {
734 $plaintext = '';
737 $last_pos = strlen($ciphertext) & 0xFFFFFFF8;
738 $plaintext.= $last_pos ? mdecrypt_generic($this->demcrypt, substr($ciphertext, 0, $last_pos)) : '';
740 if (strlen($ciphertext) & 0x7) {
741 if (strlen($plaintext)) {
742 $this->decryptIV = substr($ciphertext, $last_pos - 8, 8);
744 $this->decryptIV = mcrypt_generic($this->ecb, $this->decryptIV);
745 $this->debuffer = substr($ciphertext, $last_pos);
746 $plaintext.= $this->debuffer ^ $this->decryptIV;
749 return $plaintext;
752 if (!$this->continuousBuffer) {
753 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
756 return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
759 if (strlen($this->key) <= 8) {
760 $this->des[0]->mode = $this->mode;
761 $plaintext = $this->des[0]->decrypt($ciphertext);
762 return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
765 $des = $this->des;
767 $buffer = &$this->enbuffer;
768 $continuousBuffer = $this->continuousBuffer;
769 $plaintext = '';
770 switch ($this->mode) {
771 case CRYPT_DES_MODE_ECB:
772 for ($i = 0; $i < strlen($ciphertext); $i+=8) {
773 $block = substr($ciphertext, $i, 8);
774 $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
775 $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
776 $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
777 $plaintext.= $block;
779 break;
780 case CRYPT_DES_MODE_CBC:
781 $xor = $this->decryptIV;
782 for ($i = 0; $i < strlen($ciphertext); $i+=8) {
783 $orig = $block = substr($ciphertext, $i, 8);
784 $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
785 $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
786 $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
787 $plaintext.= $block ^ $xor;
788 $xor = $orig;
790 if ($this->continuousBuffer) {
791 $this->decryptIV = $xor;
793 break;
794 case CRYPT_DES_MODE_CTR:
795 $xor = $this->decryptIV;
796 if (strlen($buffer['ciphertext'])) {
797 for ($i = 0; $i < strlen($ciphertext); $i+=8) {
798 $block = substr($ciphertext, $i, 8);
799 $key = $this->_generate_xor(8, $xor);
800 $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
801 $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
802 $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
803 $buffer['ciphertext'].= $key;
804 $key = $this->_string_shift($buffer['ciphertext'], 8);
805 $plaintext.= $block ^ $key;
807 } else {
808 for ($i = 0; $i < strlen($ciphertext); $i+=8) {
809 $block = substr($ciphertext, $i, 8);
810 $key = $this->_generate_xor(8, $xor);
811 $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
812 $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
813 $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
814 $plaintext.= $block ^ $key;
817 if ($this->continuousBuffer) {
818 $this->decryptIV = $xor;
819 if ($start = strlen($plaintext) & 7) {
820 $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
823 break;
824 case CRYPT_DES_MODE_CFB:
825 if (!empty($buffer['ciphertext'])) {
826 $plaintext = $ciphertext ^ substr($this->decryptIV, strlen($buffer['ciphertext']));
827 $buffer['ciphertext'].= substr($ciphertext, 0, strlen($plaintext));
828 if (strlen($buffer['ciphertext']) == 8) {
829 $xor = $des[0]->_processBlock($buffer['ciphertext'], CRYPT_DES_ENCRYPT);
830 $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
831 $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
832 $buffer['ciphertext'] = '';
834 $start = strlen($plaintext);
835 $block = $this->decryptIV;
836 } else {
837 $plaintext = '';
838 $xor = $des[0]->_processBlock($this->decryptIV, CRYPT_DES_ENCRYPT);
839 $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
840 $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
841 $start = 0;
844 for ($i = $start; $i < strlen($ciphertext); $i+=8) {
845 $block = substr($ciphertext, $i, 8);
846 $plaintext.= $block ^ $xor;
847 if ($continuousBuffer && strlen($block) != 8) {
848 $buffer['ciphertext'].= $block;
849 $block = $xor;
850 } else if (strlen($block) == 8) {
851 $xor = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
852 $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
853 $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
856 if ($this->continuousBuffer) {
857 $this->decryptIV = $block;
859 break;
860 case CRYPT_DES_MODE_OFB:
861 $xor = $this->decryptIV;
862 if (strlen($buffer)) {
863 for ($i = 0; $i < strlen($ciphertext); $i+=8) {
864 $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
865 $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
866 $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
867 $buffer.= $xor;
868 $key = $this->_string_shift($buffer, 8);
869 $plaintext.= substr($ciphertext, $i, 8) ^ $key;
871 } else {
872 for ($i = 0; $i < strlen($ciphertext); $i+=8) {
873 $xor = $des[0]->_processBlock($xor, CRYPT_DES_ENCRYPT);
874 $xor = $des[1]->_processBlock($xor, CRYPT_DES_DECRYPT);
875 $xor = $des[2]->_processBlock($xor, CRYPT_DES_ENCRYPT);
876 $plaintext.= substr($ciphertext, $i, 8) ^ $xor;
878 $key = $xor;
880 if ($this->continuousBuffer) {
881 $this->decryptIV = $xor;
882 if ($start = strlen($ciphertext) & 7) {
883 $buffer = substr($key, $start) . $buffer;
888 return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
892 * Treat consecutive "packets" as if they are a continuous buffer.
894 * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
895 * will yield different outputs:
897 * <code>
898 * echo $des->encrypt(substr($plaintext, 0, 8));
899 * echo $des->encrypt(substr($plaintext, 8, 8));
900 * </code>
901 * <code>
902 * echo $des->encrypt($plaintext);
903 * </code>
905 * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
906 * another, as demonstrated with the following:
908 * <code>
909 * $des->encrypt(substr($plaintext, 0, 8));
910 * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
911 * </code>
912 * <code>
913 * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
914 * </code>
916 * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
917 * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
918 * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
920 * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
921 * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
922 * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
923 * however, they are also less intuitive and more likely to cause you problems.
925 * @see Crypt_TripleDES::disableContinuousBuffer()
926 * @access public
928 function enableContinuousBuffer()
930 $this->continuousBuffer = true;
931 if ($this->mode == CRYPT_DES_MODE_3CBC) {
932 $this->des[0]->enableContinuousBuffer();
933 $this->des[1]->enableContinuousBuffer();
934 $this->des[2]->enableContinuousBuffer();
939 * Treat consecutive packets as if they are a discontinuous buffer.
941 * The default behavior.
943 * @see Crypt_TripleDES::enableContinuousBuffer()
944 * @access public
946 function disableContinuousBuffer()
948 $this->continuousBuffer = false;
949 $this->encryptIV = $this->iv;
950 $this->decryptIV = $this->iv;
952 if ($this->mode == CRYPT_DES_MODE_3CBC) {
953 $this->des[0]->disableContinuousBuffer();
954 $this->des[1]->disableContinuousBuffer();
955 $this->des[2]->disableContinuousBuffer();
960 * Pad "packets".
962 * DES works by encrypting eight bytes at a time. If you ever need to encrypt or decrypt something that's not
963 * a multiple of eight, it becomes necessary to pad the input so that it's length is a multiple of eight.
965 * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH1,
966 * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
967 * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
968 * transmitted separately)
970 * @see Crypt_TripleDES::disablePadding()
971 * @access public
973 function enablePadding()
975 $this->padding = true;
979 * Do not pad packets.
981 * @see Crypt_TripleDES::enablePadding()
982 * @access public
984 function disablePadding()
986 $this->padding = false;
990 * Pads a string
992 * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize (8).
993 * 8 - (strlen($text) & 7) bytes are added, each of which is equal to chr(8 - (strlen($text) & 7)
995 * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
996 * and padding will, hence forth, be enabled.
998 * @see Crypt_TripleDES::_unpad()
999 * @access private
1001 function _pad($text)
1003 $length = strlen($text);
1005 if (!$this->padding) {
1006 if (($length & 7) == 0) {
1007 return $text;
1008 } else {
1009 user_error("The plaintext's length ($length) is not a multiple of the block size (8)", E_USER_NOTICE);
1010 $this->padding = true;
1014 $pad = 8 - ($length & 7);
1015 return str_pad($text, $length + $pad, chr($pad));
1019 * Unpads a string
1021 * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
1022 * and false will be returned.
1024 * @see Crypt_TripleDES::_pad()
1025 * @access private
1027 function _unpad($text)
1029 if (!$this->padding) {
1030 return $text;
1033 $length = ord($text[strlen($text) - 1]);
1035 if (!$length || $length > 8) {
1036 return false;
1039 return substr($text, 0, -$length);
1043 * String Shift
1045 * Inspired by array_shift
1047 * @param String $string
1048 * @param optional Integer $index
1049 * @return String
1050 * @access private
1052 function _string_shift(&$string, $index = 1)
1054 $substr = substr($string, 0, $index);
1055 $string = substr($string, $index);
1056 return $substr;
1060 // vim: ts=4:sw=4:et:
1061 // vim6: fdl=1: