2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
\r
5 * Pure-PHP implementation of Triple DES.
\r
7 * Uses mcrypt, if available, and an internal implementation, otherwise. Operates in the EDE3 mode (encrypt-decrypt-encrypt).
\r
9 * PHP versions 4 and 5
\r
11 * Here's a short example of how to use this library:
\r
14 * include('Crypt/TripleDES.php');
\r
16 * $des = new Crypt_TripleDES();
\r
18 * $des->setKey('abcdefghijklmnopqrstuvwx');
\r
20 * $size = 10 * 1024;
\r
22 * for ($i = 0; $i < $size; $i++) {
\r
26 * echo $des->decrypt($des->encrypt($plaintext));
\r
30 * LICENSE: This library is free software; you can redistribute it and/or
\r
31 * modify it under the terms of the GNU Lesser General Public
\r
32 * License as published by the Free Software Foundation; either
\r
33 * version 2.1 of the License, or (at your option) any later version.
\r
35 * This library is distributed in the hope that it will be useful,
\r
36 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
37 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
\r
38 * Lesser General Public License for more details.
\r
40 * You should have received a copy of the GNU Lesser General Public
\r
41 * License along with this library; if not, write to the Free Software
\r
42 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
\r
46 * @package Crypt_TripleDES
\r
47 * @author Jim Wigginton <terrafrost@php.net>
\r
48 * @copyright MMVII Jim Wigginton
\r
49 * @license http://www.gnu.org/licenses/lgpl.txt
\r
50 * @version $Id: TripleDES.php,v 1.13 2010/02/26 03:40:25 terrafrost Exp $
\r
51 * @link http://phpseclib.sourceforge.net
\r
57 require_once 'DES.php';
\r
60 * Encrypt / decrypt using inner chaining
\r
62 * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3).
\r
64 define('CRYPT_DES_MODE_3CBC', 3);
\r
67 * Encrypt / decrypt using outer chaining
\r
69 * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC.
\r
71 define('CRYPT_DES_MODE_CBC3', CRYPT_DES_MODE_CBC);
\r
74 * Pure-PHP implementation of Triple DES.
\r
76 * @author Jim Wigginton <terrafrost@php.net>
\r
79 * @package Crypt_TerraDES
\r
81 class Crypt_TripleDES {
\r
85 * @see Crypt_TripleDES::setKey()
\r
89 var $key = "\0\0\0\0\0\0\0\0";
\r
92 * The Encryption Mode
\r
94 * @see Crypt_TripleDES::Crypt_TripleDES()
\r
98 var $mode = CRYPT_DES_MODE_CBC;
\r
101 * Continuous Buffer status
\r
103 * @see Crypt_TripleDES::enableContinuousBuffer()
\r
107 var $continuousBuffer = false;
\r
112 * @see Crypt_TripleDES::enablePadding()
\r
116 var $padding = true;
\r
119 * The Initialization Vector
\r
121 * @see Crypt_TripleDES::setIV()
\r
125 var $iv = "\0\0\0\0\0\0\0\0";
\r
128 * A "sliding" Initialization Vector
\r
130 * @see Crypt_TripleDES::enableContinuousBuffer()
\r
134 var $encryptIV = "\0\0\0\0\0\0\0\0";
\r
137 * A "sliding" Initialization Vector
\r
139 * @see Crypt_TripleDES::enableContinuousBuffer()
\r
143 var $decryptIV = "\0\0\0\0\0\0\0\0";
\r
146 * The Crypt_DES objects
\r
154 * mcrypt resource for encryption
\r
156 * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
\r
157 * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
\r
159 * @see Crypt_AES::encrypt()
\r
166 * mcrypt resource for decryption
\r
168 * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
\r
169 * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
\r
171 * @see Crypt_AES::decrypt()
\r
178 * Does the (en|de)mcrypt resource need to be (re)initialized?
\r
185 var $changed = true;
\r
188 * Default Constructor.
\r
190 * Determines whether or not the mcrypt extension should be used. $mode should only, at present, be
\r
191 * CRYPT_DES_MODE_ECB or CRYPT_DES_MODE_CBC. If not explictly set, CRYPT_DES_MODE_CBC will be used.
\r
193 * @param optional Integer $mode
\r
194 * @return Crypt_TripleDES
\r
197 function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC)
\r
199 if ( !defined('CRYPT_DES_MODE') ) {
\r
201 case extension_loaded('mcrypt'):
\r
202 // i'd check to see if des was supported, by doing in_array('des', mcrypt_list_algorithms('')),
\r
203 // but since that can be changed after the object has been created, there doesn't seem to be
\r
204 // a lot of point...
\r
205 define('CRYPT_DES_MODE', CRYPT_DES_MODE_MCRYPT);
\r
208 define('CRYPT_DES_MODE', CRYPT_DES_MODE_INTERNAL);
\r
212 if ( $mode == CRYPT_DES_MODE_3CBC ) {
\r
213 $this->mode = CRYPT_DES_MODE_3CBC;
\r
214 $this->des = array(
\r
215 new Crypt_DES(CRYPT_DES_MODE_CBC),
\r
216 new Crypt_DES(CRYPT_DES_MODE_CBC),
\r
217 new Crypt_DES(CRYPT_DES_MODE_CBC)
\r
220 // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
\r
221 $this->des[0]->disablePadding();
\r
222 $this->des[1]->disablePadding();
\r
223 $this->des[2]->disablePadding();
\r
228 switch ( CRYPT_DES_MODE ) {
\r
229 case CRYPT_DES_MODE_MCRYPT:
\r
231 case CRYPT_DES_MODE_ECB:
\r
232 $this->mode = MCRYPT_MODE_ECB;
\r
234 case CRYPT_DES_MODE_CTR:
\r
235 $this->mode = 'ctr';
\r
237 case CRYPT_DES_MODE_CBC:
\r
239 $this->mode = MCRYPT_MODE_CBC;
\r
244 $this->des = array(
\r
245 new Crypt_DES(CRYPT_DES_MODE_ECB),
\r
246 new Crypt_DES(CRYPT_DES_MODE_ECB),
\r
247 new Crypt_DES(CRYPT_DES_MODE_ECB)
\r
250 // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
\r
251 $this->des[0]->disablePadding();
\r
252 $this->des[1]->disablePadding();
\r
253 $this->des[2]->disablePadding();
\r
256 case CRYPT_DES_MODE_ECB:
\r
257 case CRYPT_DES_MODE_CTR:
\r
258 case CRYPT_DES_MODE_CBC:
\r
259 $this->mode = $mode;
\r
262 $this->mode = CRYPT_DES_MODE_CBC;
\r
270 * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
\r
271 * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate.
\r
273 * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
\r
275 * If the key is not explicitly set, it'll be assumed to be all zero's.
\r
278 * @param String $key
\r
280 function setKey($key)
\r
282 $length = strlen($key);
\r
284 $key = str_pad($key, 24, chr(0));
\r
285 // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
\r
286 // http://php.net/function.mcrypt-encrypt#47973
\r
287 //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
\r
291 case CRYPT_DES_MODE == CRYPT_DES_MODE_INTERNAL:
\r
292 case $this->mode == CRYPT_DES_MODE_3CBC:
\r
293 $this->des[0]->setKey(substr($key, 0, 8));
\r
294 $this->des[1]->setKey(substr($key, 8, 8));
\r
295 $this->des[2]->setKey(substr($key, 16, 8));
\r
297 $this->changed = true;
\r
301 * Sets the initialization vector. (optional)
\r
303 * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explictly set, it'll be assumed
\r
304 * to be all zero's.
\r
307 * @param String $iv
\r
309 function setIV($iv)
\r
311 $this->encryptIV = $this->decryptIV = $this->iv = str_pad(substr($iv, 0, 8), 8, chr(0));
\r
312 if ($this->mode == CRYPT_DES_MODE_3CBC) {
\r
313 $this->des[0]->setIV($iv);
\r
314 $this->des[1]->setIV($iv);
\r
315 $this->des[2]->setIV($iv);
\r
317 $this->changed = true;
\r
321 * Generate CTR XOR encryption key
\r
323 * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
\r
324 * plaintext / ciphertext in CTR mode.
\r
326 * @see Crypt_DES::decrypt()
\r
327 * @see Crypt_DES::encrypt()
\r
329 * @param Integer $length
\r
330 * @param String $iv
\r
332 function _generate_xor($length, &$iv)
\r
335 $num_blocks = ($length + 7) >> 3;
\r
336 for ($i = 0; $i < $num_blocks; $i++) {
\r
338 for ($j = 4; $j <= 8; $j+=4) {
\r
339 $temp = substr($iv, -$j, 4);
\r
341 case "\xFF\xFF\xFF\xFF":
\r
342 $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
\r
344 case "\x7F\xFF\xFF\xFF":
\r
345 $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
\r
348 extract(unpack('Ncount', $temp));
\r
349 $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
\r
359 * Encrypts a message.
\r
362 * @param String $plaintext
\r
364 function encrypt($plaintext)
\r
366 if ($this->mode != CRYPT_DES_MODE_CTR && $this->mode != 'ctr') {
\r
367 $plaintext = $this->_pad($plaintext);
\r
370 // if the key is smaller then 8, do what we'd normally do
\r
371 if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
\r
372 $ciphertext = $this->des[2]->encrypt($this->des[1]->decrypt($this->des[0]->encrypt($plaintext)));
\r
374 return $ciphertext;
\r
377 if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
\r
378 if ($this->changed) {
\r
379 if (!isset($this->enmcrypt)) {
\r
380 $this->enmcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
\r
382 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
\r
383 $this->changed = false;
\r
386 $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
\r
388 if (!$this->continuousBuffer) {
\r
389 mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
\r
392 return $ciphertext;
\r
395 if (strlen($this->key) <= 8) {
\r
396 $this->des[0]->mode = $this->mode;
\r
398 return $this->des[0]->encrypt($plaintext);
\r
401 // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
\r
402 // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
\r
403 $plaintext = str_pad($plaintext, ceil(strlen($plaintext) / 8) * 8, chr(0));
\r
408 switch ($this->mode) {
\r
409 case CRYPT_DES_MODE_ECB:
\r
410 for ($i = 0; $i < strlen($plaintext); $i+=8) {
\r
411 $block = substr($plaintext, $i, 8);
\r
412 $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
\r
413 $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
\r
414 $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
\r
415 $ciphertext.= $block;
\r
418 case CRYPT_DES_MODE_CBC:
\r
419 $xor = $this->encryptIV;
\r
420 for ($i = 0; $i < strlen($plaintext); $i+=8) {
\r
421 $block = substr($plaintext, $i, 8) ^ $xor;
\r
422 $block = $des[0]->_processBlock($block, CRYPT_DES_ENCRYPT);
\r
423 $block = $des[1]->_processBlock($block, CRYPT_DES_DECRYPT);
\r
424 $block = $des[2]->_processBlock($block, CRYPT_DES_ENCRYPT);
\r
426 $ciphertext.= $block;
\r
428 if ($this->continuousBuffer) {
\r
429 $this->encryptIV = $xor;
\r
432 case CRYPT_DES_MODE_CTR:
\r
433 $xor = $this->encryptIV;
\r
434 for ($i = 0; $i < strlen($plaintext); $i+=8) {
\r
435 $key = $this->_generate_xor(8, $xor);
\r
436 $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
\r
437 $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
\r
438 $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
\r
439 $block = substr($plaintext, $i, 8);
\r
440 $ciphertext.= $block ^ $key;
\r
442 if ($this->continuousBuffer) {
\r
443 $this->encryptIV = $xor;
\r
447 return $ciphertext;
\r
451 * Decrypts a message.
\r
454 * @param String $ciphertext
\r
456 function decrypt($ciphertext)
\r
458 if ($this->mode == CRYPT_DES_MODE_3CBC && strlen($this->key) > 8) {
\r
459 $plaintext = $this->des[0]->decrypt($this->des[1]->encrypt($this->des[2]->decrypt($ciphertext)));
\r
461 return $this->_unpad($plaintext);
\r
464 // we pad with chr(0) since that's what mcrypt_generic does. to quote from http://php.net/function.mcrypt-generic :
\r
465 // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
\r
466 $ciphertext = str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, chr(0));
\r
468 if ( CRYPT_DES_MODE == CRYPT_DES_MODE_MCRYPT ) {
\r
469 if ($this->changed) {
\r
470 if (!isset($this->demcrypt)) {
\r
471 $this->demcrypt = mcrypt_module_open(MCRYPT_3DES, '', $this->mode, '');
\r
473 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
\r
474 $this->changed = false;
\r
477 $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
\r
479 if (!$this->continuousBuffer) {
\r
480 mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
\r
483 return $this->mode != 'ctr' ? $this->_unpad($plaintext) : $plaintext;
\r
486 if (strlen($this->key) <= 8) {
\r
487 $this->des[0]->mode = $this->mode;
\r
489 return $this->_unpad($this->des[0]->decrypt($plaintext));
\r
495 switch ($this->mode) {
\r
496 case CRYPT_DES_MODE_ECB:
\r
497 for ($i = 0; $i < strlen($ciphertext); $i+=8) {
\r
498 $block = substr($ciphertext, $i, 8);
\r
499 $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
\r
500 $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
\r
501 $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
\r
502 $plaintext.= $block;
\r
505 case CRYPT_DES_MODE_CBC:
\r
506 $xor = $this->decryptIV;
\r
507 for ($i = 0; $i < strlen($ciphertext); $i+=8) {
\r
508 $orig = $block = substr($ciphertext, $i, 8);
\r
509 $block = $des[2]->_processBlock($block, CRYPT_DES_DECRYPT);
\r
510 $block = $des[1]->_processBlock($block, CRYPT_DES_ENCRYPT);
\r
511 $block = $des[0]->_processBlock($block, CRYPT_DES_DECRYPT);
\r
512 $plaintext.= $block ^ $xor;
\r
515 if ($this->continuousBuffer) {
\r
516 $this->decryptIV = $xor;
\r
519 case CRYPT_DES_MODE_CTR:
\r
520 $xor = $this->decryptIV;
\r
521 for ($i = 0; $i < strlen($ciphertext); $i+=8) {
\r
522 $key = $this->_generate_xor(8, $xor);
\r
523 $key = $des[0]->_processBlock($key, CRYPT_DES_ENCRYPT);
\r
524 $key = $des[1]->_processBlock($key, CRYPT_DES_DECRYPT);
\r
525 $key = $des[2]->_processBlock($key, CRYPT_DES_ENCRYPT);
\r
526 $block = substr($ciphertext, $i, 8);
\r
527 $plaintext.= $block ^ $key;
\r
529 if ($this->continuousBuffer) {
\r
530 $this->decryptIV = $xor;
\r
534 return $this->mode != CRYPT_DES_MODE_CTR ? $this->_unpad($plaintext) : $plaintext;
\r
538 * Treat consecutive "packets" as if they are a continuous buffer.
\r
540 * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets
\r
541 * will yield different outputs:
\r
544 * echo $des->encrypt(substr($plaintext, 0, 8));
\r
545 * echo $des->encrypt(substr($plaintext, 8, 8));
\r
548 * echo $des->encrypt($plaintext);
\r
551 * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
\r
552 * another, as demonstrated with the following:
\r
555 * $des->encrypt(substr($plaintext, 0, 8));
\r
556 * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
\r
559 * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
\r
562 * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
\r
563 * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
\r
564 * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
\r
566 * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
\r
567 * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
\r
568 * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
\r
569 * however, they are also less intuitive and more likely to cause you problems.
\r
571 * @see Crypt_TripleDES::disableContinuousBuffer()
\r
574 function enableContinuousBuffer()
\r
576 $this->continuousBuffer = true;
\r
577 if ($this->mode == CRYPT_DES_MODE_3CBC) {
\r
578 $this->des[0]->enableContinuousBuffer();
\r
579 $this->des[1]->enableContinuousBuffer();
\r
580 $this->des[2]->enableContinuousBuffer();
\r
585 * Treat consecutive packets as if they are a discontinuous buffer.
\r
587 * The default behavior.
\r
589 * @see Crypt_TripleDES::enableContinuousBuffer()
\r
592 function disableContinuousBuffer()
\r
594 $this->continuousBuffer = false;
\r
595 $this->encryptIV = $this->iv;
\r
596 $this->decryptIV = $this->iv;
\r
598 if ($this->mode == CRYPT_DES_MODE_3CBC) {
\r
599 $this->des[0]->disableContinuousBuffer();
\r
600 $this->des[1]->disableContinuousBuffer();
\r
601 $this->des[2]->disableContinuousBuffer();
\r
608 * DES works by encrypting eight bytes at a time. If you ever need to encrypt or decrypt something that's not
\r
609 * a multiple of eight, it becomes necessary to pad the input so that it's length is a multiple of eight.
\r
611 * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH1,
\r
612 * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
\r
613 * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
\r
614 * transmitted separately)
\r
616 * @see Crypt_TripleDES::disablePadding()
\r
619 function enablePadding()
\r
621 $this->padding = true;
\r
625 * Do not pad packets.
\r
627 * @see Crypt_TripleDES::enablePadding()
\r
630 function disablePadding()
\r
632 $this->padding = false;
\r
638 * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize (8).
\r
639 * 8 - (strlen($text) & 7) bytes are added, each of which is equal to chr(8 - (strlen($text) & 7)
\r
641 * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
\r
642 * and padding will, hence forth, be enabled.
\r
644 * @see Crypt_TripleDES::_unpad()
\r
647 function _pad($text)
\r
649 $length = strlen($text);
\r
651 if (!$this->padding) {
\r
652 if (($length & 7) == 0) {
\r
655 user_error("The plaintext's length ($length) is not a multiple of the block size (8)", E_USER_NOTICE);
\r
656 $this->padding = true;
\r
660 $pad = 8 - ($length & 7);
\r
661 return str_pad($text, $length + $pad, chr($pad));
\r
667 * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
\r
668 * and false will be returned.
\r
670 * @see Crypt_TripleDES::_pad()
\r
673 function _unpad($text)
\r
675 if (!$this->padding) {
\r
679 $length = ord($text[strlen($text) - 1]);
\r
681 if (!$length || $length > 8) {
\r
685 return substr($text, 0, -$length);
\r
689 // vim: ts=4:sw=4:et:
\r