Subversion Repositories cheapmusic

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
103 - 1
<?php
2
 
3
/**
4
 * Pure-PHP implementation of Triple DES.
5
 *
6
 * Uses mcrypt, if available, and an internal implementation, otherwise.  Operates in the EDE3 mode (encrypt-decrypt-encrypt).
7
 *
8
 * PHP version 5
9
 *
10
 * Here's a short example of how to use this library:
11
 * <code>
12
 * <?php
13
 *    include 'vendor/autoload.php';
14
 *
15
 *    $des = new \phpseclib\Crypt\TripleDES();
16
 *
17
 *    $des->setKey('abcdefghijklmnopqrstuvwx');
18
 *
19
 *    $size = 10 * 1024;
20
 *    $plaintext = '';
21
 *    for ($i = 0; $i < $size; $i++) {
22
 *        $plaintext.= 'a';
23
 *    }
24
 *
25
 *    echo $des->decrypt($des->encrypt($plaintext));
26
 * ?>
27
 * </code>
28
 *
29
 * @category  Crypt
30
 * @package   TripleDES
31
 * @author    Jim Wigginton <terrafrost@php.net>
32
 * @copyright 2007 Jim Wigginton
33
 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
34
 * @link      http://phpseclib.sourceforge.net
35
 */
36
 
37
namespace phpseclib\Crypt;
38
 
39
/**
40
 * Pure-PHP implementation of Triple DES.
41
 *
42
 * @package TripleDES
43
 * @author  Jim Wigginton <terrafrost@php.net>
44
 * @access  public
45
 */
46
class TripleDES extends DES
47
{
48
    /**
49
     * Encrypt / decrypt using inner chaining
50
     *
51
     * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (self::MODE_CBC3).
52
     */
53
    const MODE_3CBC = -2;
54
 
55
    /**
56
     * Encrypt / decrypt using outer chaining
57
     *
58
     * Outer chaining is used by SSH-2 and when the mode is set to \phpseclib\Crypt\Base::MODE_CBC.
59
     */
60
    const MODE_CBC3 = Base::MODE_CBC;
61
 
62
    /**
63
     * Key Length (in bytes)
64
     *
65
     * @see \phpseclib\Crypt\TripleDES::setKeyLength()
66
     * @var int
67
     * @access private
68
     */
69
    var $key_length = 24;
70
 
71
    /**
72
     * The default salt used by setPassword()
73
     *
74
     * @see \phpseclib\Crypt\Base::password_default_salt
75
     * @see \phpseclib\Crypt\Base::setPassword()
76
     * @var string
77
     * @access private
78
     */
79
    var $password_default_salt = 'phpseclib';
80
 
81
    /**
82
     * The mcrypt specific name of the cipher
83
     *
84
     * @see \phpseclib\Crypt\DES::cipher_name_mcrypt
85
     * @see \phpseclib\Crypt\Base::cipher_name_mcrypt
86
     * @var string
87
     * @access private
88
     */
89
    var $cipher_name_mcrypt = 'tripledes';
90
 
91
    /**
92
     * Optimizing value while CFB-encrypting
93
     *
94
     * @see \phpseclib\Crypt\Base::cfb_init_len
95
     * @var int
96
     * @access private
97
     */
98
    var $cfb_init_len = 750;
99
 
100
    /**
101
     * max possible size of $key
102
     *
103
     * @see self::setKey()
104
     * @see \phpseclib\Crypt\DES::setKey()
105
     * @var string
106
     * @access private
107
     */
108
    var $key_length_max = 24;
109
 
110
    /**
111
     * Internal flag whether using self::MODE_3CBC or not
112
     *
113
     * @var bool
114
     * @access private
115
     */
116
    var $mode_3cbc;
117
 
118
    /**
119
     * The \phpseclib\Crypt\DES objects
120
     *
121
     * Used only if $mode_3cbc === true
122
     *
123
     * @var array
124
     * @access private
125
     */
126
    var $des;
127
 
128
    /**
129
     * Default Constructor.
130
     *
131
     * Determines whether or not the mcrypt extension should be used.
132
     *
133
     * $mode could be:
134
     *
135
     * - \phpseclib\Crypt\Base::MODE_ECB
136
     *
137
     * - \phpseclib\Crypt\Base::MODE_CBC
138
     *
139
     * - \phpseclib\Crypt\Base::MODE_CTR
140
     *
141
     * - \phpseclib\Crypt\Base::MODE_CFB
142
     *
143
     * - \phpseclib\Crypt\Base::MODE_OFB
144
     *
145
     * - \phpseclib\Crypt\TripleDES::MODE_3CBC
146
     *
147
     * If not explicitly set, \phpseclib\Crypt\Base::MODE_CBC will be used.
148
     *
149
     * @see \phpseclib\Crypt\DES::__construct()
150
     * @see \phpseclib\Crypt\Base::__construct()
151
     * @param int $mode
152
     * @access public
153
     */
154
    function __construct($mode = Base::MODE_CBC)
155
    {
156
        switch ($mode) {
157
            // In case of self::MODE_3CBC, we init as CRYPT_DES_MODE_CBC
158
            // and additional flag us internally as 3CBC
159
            case self::MODE_3CBC:
160
                parent::__construct(Base::MODE_CBC);
161
                $this->mode_3cbc = true;
162
 
163
                // This three $des'es will do the 3CBC work (if $key > 64bits)
164
                $this->des = array(
165
                    new DES(Base::MODE_CBC),
166
                    new DES(Base::MODE_CBC),
167
                    new DES(Base::MODE_CBC),
168
                );
169
 
170
                // we're going to be doing the padding, ourselves, so disable it in the \phpseclib\Crypt\DES objects
171
                $this->des[0]->disablePadding();
172
                $this->des[1]->disablePadding();
173
                $this->des[2]->disablePadding();
174
                break;
175
            // If not 3CBC, we init as usual
176
            default:
177
                parent::__construct($mode);
178
        }
179
    }
180
 
181
    /**
182
     * Test for engine validity
183
     *
184
     * This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine()
185
     *
186
     * @see \phpseclib\Crypt\Base::__construct()
187
     * @param int $engine
188
     * @access public
189
     * @return bool
190
     */
191
    function isValidEngine($engine)
192
    {
193
        if ($engine == self::ENGINE_OPENSSL) {
194
            $this->cipher_name_openssl_ecb = 'des-ede3';
195
            $mode = $this->_openssl_translate_mode();
196
            $this->cipher_name_openssl = $mode == 'ecb' ? 'des-ede3' : 'des-ede3-' . $mode;
197
        }
198
 
199
        return parent::isValidEngine($engine);
200
    }
201
 
202
    /**
203
     * Sets the initialization vector. (optional)
204
     *
205
     * SetIV is not required when \phpseclib\Crypt\Base::MODE_ECB is being used.  If not explicitly set, it'll be assumed
206
     * to be all zero's.
207
     *
208
     * @see \phpseclib\Crypt\Base::setIV()
209
     * @access public
210
     * @param string $iv
211
     */
212
    function setIV($iv)
213
    {
214
        parent::setIV($iv);
215
        if ($this->mode_3cbc) {
216
            $this->des[0]->setIV($iv);
217
            $this->des[1]->setIV($iv);
218
            $this->des[2]->setIV($iv);
219
        }
220
    }
221
 
222
    /**
223
     * Sets the key length.
224
     *
225
     * Valid key lengths are 64, 128 and 192
226
     *
227
     * @see \phpseclib\Crypt\Base:setKeyLength()
228
     * @access public
229
     * @param int $length
230
     */
231
    function setKeyLength($length)
232
    {
233
        $length >>= 3;
234
        switch (true) {
235
            case $length <= 8:
236
                $this->key_length = 8;
237
                break;
238
            case $length <= 16:
239
                $this->key_length = 16;
240
                break;
241
            default:
242
                $this->key_length = 24;
243
        }
244
 
245
        parent::setKeyLength($length);
246
    }
247
 
248
    /**
249
     * Sets the key.
250
     *
251
     * Keys can be of any length.  Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
252
     * 192-bit (eg. strlen($key) == 24) keys.  This function pads and truncates $key as appropriate.
253
     *
254
     * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
255
     *
256
     * If the key is not explicitly set, it'll be assumed to be all null bytes.
257
     *
258
     * @access public
259
     * @see \phpseclib\Crypt\DES::setKey()
260
     * @see \phpseclib\Crypt\Base::setKey()
261
     * @param string $key
262
     */
263
    function setKey($key)
264
    {
265
        $length = $this->explicit_key_length ? $this->key_length : strlen($key);
266
        if ($length > 8) {
267
            $key = str_pad(substr($key, 0, 24), 24, chr(0));
268
            // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
269
            // http://php.net/function.mcrypt-encrypt#47973
270
            $key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
271
        } else {
272
            $key = str_pad($key, 8, chr(0));
273
        }
274
        parent::setKey($key);
275
 
276
        // And in case of self::MODE_3CBC:
277
        // if key <= 64bits we not need the 3 $des to work,
278
        // because we will then act as regular DES-CBC with just a <= 64bit key.
279
        // So only if the key > 64bits (> 8 bytes) we will call setKey() for the 3 $des.
280
        if ($this->mode_3cbc && $length > 8) {
281
            $this->des[0]->setKey(substr($key,  0, 8));
282
            $this->des[1]->setKey(substr($key,  8, 8));
283
            $this->des[2]->setKey(substr($key, 16, 8));
284
        }
285
    }
286
 
287
    /**
288
     * Encrypts a message.
289
     *
290
     * @see \phpseclib\Crypt\Base::encrypt()
291
     * @access public
292
     * @param string $plaintext
293
     * @return string $cipertext
294
     */
295
    function encrypt($plaintext)
296
    {
297
        // parent::en/decrypt() is able to do all the work for all modes and keylengths,
298
        // except for: self::MODE_3CBC (inner chaining CBC) with a key > 64bits
299
 
300
        // if the key is smaller then 8, do what we'd normally do
301
        if ($this->mode_3cbc && strlen($this->key) > 8) {
302
            return $this->des[2]->encrypt(
303
                $this->des[1]->decrypt(
304
                    $this->des[0]->encrypt(
305
                        $this->_pad($plaintext)
306
                    )
307
                )
308
            );
309
        }
310
 
311
        return parent::encrypt($plaintext);
312
    }
313
 
314
    /**
315
     * Decrypts a message.
316
     *
317
     * @see \phpseclib\Crypt\Base::decrypt()
318
     * @access public
319
     * @param string $ciphertext
320
     * @return string $plaintext
321
     */
322
    function decrypt($ciphertext)
323
    {
324
        if ($this->mode_3cbc && strlen($this->key) > 8) {
325
            return $this->_unpad(
326
                $this->des[0]->decrypt(
327
                    $this->des[1]->encrypt(
328
                        $this->des[2]->decrypt(
329
                            str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, "\0")
330
                        )
331
                    )
332
                )
333
            );
334
        }
335
 
336
        return parent::decrypt($ciphertext);
337
    }
338
 
339
    /**
340
     * Treat consecutive "packets" as if they are a continuous buffer.
341
     *
342
     * Say you have a 16-byte plaintext $plaintext.  Using the default behavior, the two following code snippets
343
     * will yield different outputs:
344
     *
345
     * <code>
346
     *    echo $des->encrypt(substr($plaintext, 0, 8));
347
     *    echo $des->encrypt(substr($plaintext, 8, 8));
348
     * </code>
349
     * <code>
350
     *    echo $des->encrypt($plaintext);
351
     * </code>
352
     *
353
     * The solution is to enable the continuous buffer.  Although this will resolve the above discrepancy, it creates
354
     * another, as demonstrated with the following:
355
     *
356
     * <code>
357
     *    $des->encrypt(substr($plaintext, 0, 8));
358
     *    echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
359
     * </code>
360
     * <code>
361
     *    echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
362
     * </code>
363
     *
364
     * With the continuous buffer disabled, these would yield the same output.  With it enabled, they yield different
365
     * outputs.  The reason is due to the fact that the initialization vector's change after every encryption /
366
     * decryption round when the continuous buffer is enabled.  When it's disabled, they remain constant.
367
     *
368
     * Put another way, when the continuous buffer is enabled, the state of the \phpseclib\Crypt\DES() object changes after each
369
     * encryption / decryption round, whereas otherwise, it'd remain constant.  For this reason, it's recommended that
370
     * continuous buffers not be used.  They do offer better security and are, in fact, sometimes required (SSH uses them),
371
     * however, they are also less intuitive and more likely to cause you problems.
372
     *
373
     * @see \phpseclib\Crypt\Base::enableContinuousBuffer()
374
     * @see self::disableContinuousBuffer()
375
     * @access public
376
     */
377
    function enableContinuousBuffer()
378
    {
379
        parent::enableContinuousBuffer();
380
        if ($this->mode_3cbc) {
381
            $this->des[0]->enableContinuousBuffer();
382
            $this->des[1]->enableContinuousBuffer();
383
            $this->des[2]->enableContinuousBuffer();
384
        }
385
    }
386
 
387
    /**
388
     * Treat consecutive packets as if they are a discontinuous buffer.
389
     *
390
     * The default behavior.
391
     *
392
     * @see \phpseclib\Crypt\Base::disableContinuousBuffer()
393
     * @see self::enableContinuousBuffer()
394
     * @access public
395
     */
396
    function disableContinuousBuffer()
397
    {
398
        parent::disableContinuousBuffer();
399
        if ($this->mode_3cbc) {
400
            $this->des[0]->disableContinuousBuffer();
401
            $this->des[1]->disableContinuousBuffer();
402
            $this->des[2]->disableContinuousBuffer();
403
        }
404
    }
405
 
406
    /**
407
     * Creates the key schedule
408
     *
409
     * @see \phpseclib\Crypt\DES::_setupKey()
410
     * @see \phpseclib\Crypt\Base::_setupKey()
411
     * @access private
412
     */
413
    function _setupKey()
414
    {
415
        switch (true) {
416
            // if $key <= 64bits we configure our internal pure-php cipher engine
417
            // to act as regular [1]DES, not as 3DES. mcrypt.so::tripledes does the same.
418
            case strlen($this->key) <= 8:
419
                $this->des_rounds = 1;
420
                break;
421
 
422
            // otherwise, if $key > 64bits, we configure our engine to work as 3DES.
423
            default:
424
                $this->des_rounds = 3;
425
 
426
                // (only) if 3CBC is used we have, of course, to setup the $des[0-2] keys also separately.
427
                if ($this->mode_3cbc) {
428
                    $this->des[0]->_setupKey();
429
                    $this->des[1]->_setupKey();
430
                    $this->des[2]->_setupKey();
431
 
432
                    // because $des[0-2] will, now, do all the work we can return here
433
                    // not need unnecessary stress parent::_setupKey() with our, now unused, $key.
434
                    return;
435
                }
436
        }
437
        // setup our key
438
        parent::_setupKey();
439
    }
440
 
441
    /**
442
     * Sets the internal crypt engine
443
     *
444
     * @see \phpseclib\Crypt\Base::__construct()
445
     * @see \phpseclib\Crypt\Base::setPreferredEngine()
446
     * @param int $engine
447
     * @access public
448
     * @return int
449
     */
450
    function setPreferredEngine($engine)
451
    {
452
        if ($this->mode_3cbc) {
453
            $this->des[0]->setPreferredEngine($engine);
454
            $this->des[1]->setPreferredEngine($engine);
455
            $this->des[2]->setPreferredEngine($engine);
456
        }
457
 
458
        return parent::setPreferredEngine($engine);
459
    }
460
}