]> git.mxchange.org Git - friendica-addons.git/blob - securemail/vendor/phpseclib/phpseclib/phpseclib/Crypt/TripleDES.php
securemail: update pgp library
[friendica-addons.git] / securemail / vendor / phpseclib / phpseclib / phpseclib / Crypt / TripleDES.php
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 versions 4 and 5
9  *
10  * Here's a short example of how to use this library:
11  * <code>
12  * <?php
13  *    include 'Crypt/TripleDES.php';
14  *
15  *    $des = new 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  * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
30  * of this software and associated documentation files (the "Software"), to deal
31  * in the Software without restriction, including without limitation the rights
32  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33  * copies of the Software, and to permit persons to whom the Software is
34  * furnished to do so, subject to the following conditions:
35  *
36  * The above copyright notice and this permission notice shall be included in
37  * all copies or substantial portions of the Software.
38  *
39  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
45  * THE SOFTWARE.
46  *
47  * @category  Crypt
48  * @package   Crypt_TripleDES
49  * @author    Jim Wigginton <terrafrost@php.net>
50  * @copyright 2007 Jim Wigginton
51  * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
52  * @link      http://phpseclib.sourceforge.net
53  */
54
55 /**
56  * Include Crypt_DES
57  */
58 if (!class_exists('Crypt_DES')) {
59     include_once 'DES.php';
60 }
61
62 /**
63  * Encrypt / decrypt using inner chaining
64  *
65  * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3).
66  */
67 define('CRYPT_DES_MODE_3CBC', -2);
68
69 /**
70  * Encrypt / decrypt using outer chaining
71  *
72  * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC.
73  */
74 define('CRYPT_DES_MODE_CBC3', CRYPT_DES_MODE_CBC);
75
76 /**
77  * Pure-PHP implementation of Triple DES.
78  *
79  * @package Crypt_TripleDES
80  * @author  Jim Wigginton <terrafrost@php.net>
81  * @access  public
82  */
83 class Crypt_TripleDES extends Crypt_DES
84 {
85     /**
86      * The default password key_size used by setPassword()
87      *
88      * @see Crypt_DES::password_key_size
89      * @see Crypt_Base::password_key_size
90      * @see Crypt_Base::setPassword()
91      * @var Integer
92      * @access private
93      */
94     var $password_key_size = 24;
95
96     /**
97      * The default salt used by setPassword()
98      *
99      * @see Crypt_Base::password_default_salt
100      * @see Crypt_Base::setPassword()
101      * @var String
102      * @access private
103      */
104     var $password_default_salt = 'phpseclib';
105
106     /**
107      * The namespace used by the cipher for its constants.
108      *
109      * @see Crypt_DES::const_namespace
110      * @see Crypt_Base::const_namespace
111      * @var String
112      * @access private
113      */
114     var $const_namespace = 'DES';
115
116     /**
117      * The mcrypt specific name of the cipher
118      *
119      * @see Crypt_DES::cipher_name_mcrypt
120      * @see Crypt_Base::cipher_name_mcrypt
121      * @var String
122      * @access private
123      */
124     var $cipher_name_mcrypt = 'tripledes';
125
126     /**
127      * Optimizing value while CFB-encrypting
128      *
129      * @see Crypt_Base::cfb_init_len
130      * @var Integer
131      * @access private
132      */
133     var $cfb_init_len = 750;
134
135     /**
136      * max possible size of $key
137      *
138      * @see Crypt_TripleDES::setKey()
139      * @see Crypt_DES::setKey()
140      * @var String
141      * @access private
142      */
143     var $key_size_max = 24;
144
145     /**
146      * Internal flag whether using CRYPT_DES_MODE_3CBC or not
147      *
148      * @var Boolean
149      * @access private
150      */
151     var $mode_3cbc;
152
153     /**
154      * The Crypt_DES objects
155      *
156      * Used only if $mode_3cbc === true
157      *
158      * @var Array
159      * @access private
160      */
161     var $des;
162
163     /**
164      * Default Constructor.
165      *
166      * Determines whether or not the mcrypt extension should be used.
167      *
168      * $mode could be:
169      *
170      * - CRYPT_DES_MODE_ECB
171      *
172      * - CRYPT_DES_MODE_CBC
173      *
174      * - CRYPT_DES_MODE_CTR
175      *
176      * - CRYPT_DES_MODE_CFB
177      *
178      * - CRYPT_DES_MODE_OFB
179      *
180      * - CRYPT_DES_MODE_3CBC
181      *
182      * If not explicitly set, CRYPT_DES_MODE_CBC will be used.
183      *
184      * @see Crypt_DES::Crypt_DES()
185      * @see Crypt_Base::Crypt_Base()
186      * @param optional Integer $mode
187      * @access public
188      */
189     function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC)
190     {
191         switch ($mode) {
192             // In case of CRYPT_DES_MODE_3CBC, we init as CRYPT_DES_MODE_CBC
193             // and additional flag us internally as 3CBC
194             case CRYPT_DES_MODE_3CBC:
195                 parent::Crypt_Base(CRYPT_DES_MODE_CBC);
196                 $this->mode_3cbc = true;
197
198                 // This three $des'es will do the 3CBC work (if $key > 64bits)
199                 $this->des = array(
200                     new Crypt_DES(CRYPT_DES_MODE_CBC),
201                     new Crypt_DES(CRYPT_DES_MODE_CBC),
202                     new Crypt_DES(CRYPT_DES_MODE_CBC),
203                 );
204
205                 // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects
206                 $this->des[0]->disablePadding();
207                 $this->des[1]->disablePadding();
208                 $this->des[2]->disablePadding();
209                 break;
210             // If not 3CBC, we init as usual
211             default:
212                 parent::Crypt_Base($mode);
213         }
214     }
215
216     /**
217      * Sets the initialization vector. (optional)
218      *
219      * SetIV is not required when CRYPT_DES_MODE_ECB is being used.  If not explicitly set, it'll be assumed
220      * to be all zero's.
221      *
222      * @see Crypt_Base::setIV()
223      * @access public
224      * @param String $iv
225      */
226     function setIV($iv)
227     {
228         parent::setIV($iv);
229         if ($this->mode_3cbc) {
230             $this->des[0]->setIV($iv);
231             $this->des[1]->setIV($iv);
232             $this->des[2]->setIV($iv);
233         }
234     }
235
236     /**
237      * Sets the key.
238      *
239      * Keys can be of any length.  Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or
240      * 192-bit (eg. strlen($key) == 24) keys.  This function pads and truncates $key as appropriate.
241      *
242      * DES also requires that every eighth bit be a parity bit, however, we'll ignore that.
243      *
244      * If the key is not explicitly set, it'll be assumed to be all null bytes.
245      *
246      * @access public
247      * @see Crypt_DES::setKey()
248      * @see Crypt_Base::setKey()
249      * @param String $key
250      */
251     function setKey($key)
252     {
253         $length = strlen($key);
254         if ($length > 8) {
255             $key = str_pad(substr($key, 0, 24), 24, chr(0));
256             // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
257             // http://php.net/function.mcrypt-encrypt#47973
258             //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
259         } else {
260             $key = str_pad($key, 8, chr(0));
261         }
262         parent::setKey($key);
263
264         // And in case of CRYPT_DES_MODE_3CBC:
265         // if key <= 64bits we not need the 3 $des to work,
266         // because we will then act as regular DES-CBC with just a <= 64bit key.
267         // So only if the key > 64bits (> 8 bytes) we will call setKey() for the 3 $des.
268         if ($this->mode_3cbc && $length > 8) {
269             $this->des[0]->setKey(substr($key,  0, 8));
270             $this->des[1]->setKey(substr($key,  8, 8));
271             $this->des[2]->setKey(substr($key, 16, 8));
272         }
273     }
274
275     /**
276      * Encrypts a message.
277      *
278      * @see Crypt_Base::encrypt()
279      * @access public
280      * @param String $plaintext
281      * @return String $cipertext
282      */
283     function encrypt($plaintext)
284     {
285         // parent::en/decrypt() is able to do all the work for all modes and keylengths,
286         // except for: CRYPT_DES_MODE_3CBC (inner chaining CBC) with a key > 64bits
287
288         // if the key is smaller then 8, do what we'd normally do
289         if ($this->mode_3cbc && strlen($this->key) > 8) {
290             return $this->des[2]->encrypt(
291                 $this->des[1]->decrypt(
292                     $this->des[0]->encrypt(
293                         $this->_pad($plaintext)
294                     )
295                 )
296             );
297         }
298
299         return parent::encrypt($plaintext);
300     }
301
302     /**
303      * Decrypts a message.
304      *
305      * @see Crypt_Base::decrypt()
306      * @access public
307      * @param String $ciphertext
308      * @return String $plaintext
309      */
310     function decrypt($ciphertext)
311     {
312         if ($this->mode_3cbc && strlen($this->key) > 8) {
313             return $this->_unpad(
314                 $this->des[0]->decrypt(
315                     $this->des[1]->encrypt(
316                         $this->des[2]->decrypt(
317                             str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, "\0")
318                         )
319                     )
320                 )
321             );
322         }
323
324         return parent::decrypt($ciphertext);
325     }
326
327     /**
328      * Treat consecutive "packets" as if they are a continuous buffer.
329      *
330      * Say you have a 16-byte plaintext $plaintext.  Using the default behavior, the two following code snippets
331      * will yield different outputs:
332      *
333      * <code>
334      *    echo $des->encrypt(substr($plaintext, 0, 8));
335      *    echo $des->encrypt(substr($plaintext, 8, 8));
336      * </code>
337      * <code>
338      *    echo $des->encrypt($plaintext);
339      * </code>
340      *
341      * The solution is to enable the continuous buffer.  Although this will resolve the above discrepancy, it creates
342      * another, as demonstrated with the following:
343      *
344      * <code>
345      *    $des->encrypt(substr($plaintext, 0, 8));
346      *    echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
347      * </code>
348      * <code>
349      *    echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8)));
350      * </code>
351      *
352      * With the continuous buffer disabled, these would yield the same output.  With it enabled, they yield different
353      * outputs.  The reason is due to the fact that the initialization vector's change after every encryption /
354      * decryption round when the continuous buffer is enabled.  When it's disabled, they remain constant.
355      *
356      * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each
357      * encryption / decryption round, whereas otherwise, it'd remain constant.  For this reason, it's recommended that
358      * continuous buffers not be used.  They do offer better security and are, in fact, sometimes required (SSH uses them),
359      * however, they are also less intuitive and more likely to cause you problems.
360      *
361      * @see Crypt_Base::enableContinuousBuffer()
362      * @see Crypt_TripleDES::disableContinuousBuffer()
363      * @access public
364      */
365     function enableContinuousBuffer()
366     {
367         parent::enableContinuousBuffer();
368         if ($this->mode_3cbc) {
369             $this->des[0]->enableContinuousBuffer();
370             $this->des[1]->enableContinuousBuffer();
371             $this->des[2]->enableContinuousBuffer();
372         }
373     }
374
375     /**
376      * Treat consecutive packets as if they are a discontinuous buffer.
377      *
378      * The default behavior.
379      *
380      * @see Crypt_Base::disableContinuousBuffer()
381      * @see Crypt_TripleDES::enableContinuousBuffer()
382      * @access public
383      */
384     function disableContinuousBuffer()
385     {
386         parent::disableContinuousBuffer();
387         if ($this->mode_3cbc) {
388             $this->des[0]->disableContinuousBuffer();
389             $this->des[1]->disableContinuousBuffer();
390             $this->des[2]->disableContinuousBuffer();
391         }
392     }
393
394     /**
395      * Creates the key schedule
396      *
397      * @see Crypt_DES::_setupKey()
398      * @see Crypt_Base::_setupKey()
399      * @access private
400      */
401     function _setupKey()
402     {
403         switch (true) {
404             // if $key <= 64bits we configure our internal pure-php cipher engine
405             // to act as regular [1]DES, not as 3DES. mcrypt.so::tripledes does the same.
406             case strlen($this->key) <= 8:
407                 $this->des_rounds = 1;
408                 break;
409
410             // otherwise, if $key > 64bits, we configure our engine to work as 3DES.
411             default:
412                 $this->des_rounds = 3;
413
414                 // (only) if 3CBC is used we have, of course, to setup the $des[0-2] keys also separately.
415                 if ($this->mode_3cbc) {
416                     $this->des[0]->_setupKey();
417                     $this->des[1]->_setupKey();
418                     $this->des[2]->_setupKey();
419
420                     // because $des[0-2] will, now, do all the work we can return here
421                     // not need unnecessary stress parent::_setupKey() with our, now unused, $key.
422                     return;
423                 }
424         }
425         // setup our key
426         parent::_setupKey();
427     }
428 }