PageRenderTime 179ms CodeModel.GetById 86ms app.highlight 10ms RepoModel.GetById 80ms app.codeStats 0ms

/Filter/Encrypt/Mcrypt.php

https://bitbucket.org/goldie/zend-framework1
PHP | 364 lines | 192 code | 42 blank | 130 comment | 31 complexity | 487ba7c91470134c80233b48e3f821dc MD5 | raw file
  1<?php
  2/**
  3 * Zend Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the new BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 * It is also available through the world-wide-web at this URL:
 10 * http://framework.zend.com/license/new-bsd
 11 * If you did not receive a copy of the license and are unable to
 12 * obtain it through the world-wide-web, please send an email
 13 * to license@zend.com so we can send you a copy immediately.
 14 *
 15 * @category   Zend
 16 * @package    Zend_Filter
 17 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 18 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 19 * @version    $Id: Mcrypt.php 23775 2011-03-01 17:25:24Z ralph $
 20 */
 21
 22/**
 23 * @see Zend_Filter_Encrypt_Interface
 24 */
 25require_once 'Zend/Filter/Encrypt/Interface.php';
 26
 27/**
 28 * Encryption adapter for mcrypt
 29 *
 30 * @category   Zend
 31 * @package    Zend_Filter
 32 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 33 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 34 */
 35class Zend_Filter_Encrypt_Mcrypt implements Zend_Filter_Encrypt_Interface
 36{
 37    /**
 38     * Definitions for encryption
 39     * array(
 40     *     'key' => encryption key string
 41     *     'algorithm' => algorithm to use
 42     *     'algorithm_directory' => directory where to find the algorithm
 43     *     'mode' => encryption mode to use
 44     *     'modedirectory' => directory where to find the mode
 45     * )
 46     */
 47    protected $_encryption = array(
 48        'key'                 => 'ZendFramework',
 49        'algorithm'           => 'blowfish',
 50        'algorithm_directory' => '',
 51        'mode'                => 'cbc',
 52        'mode_directory'      => '',
 53        'vector'              => null,
 54        'salt'                => false
 55    );
 56
 57    /**
 58     * Internal compression
 59     *
 60     * @var array
 61     */
 62    protected $_compression;
 63
 64    protected static $_srandCalled = false;
 65
 66    /**
 67     * Class constructor
 68     *
 69     * @param string|array|Zend_Config $options Cryption Options
 70     */
 71    public function __construct($options)
 72    {
 73        if (!extension_loaded('mcrypt')) {
 74            require_once 'Zend/Filter/Exception.php';
 75            throw new Zend_Filter_Exception('This filter needs the mcrypt extension');
 76        }
 77
 78        if ($options instanceof Zend_Config) {
 79            $options = $options->toArray();
 80        } elseif (is_string($options)) {
 81            $options = array('key' => $options);
 82        } elseif (!is_array($options)) {
 83            require_once 'Zend/Filter/Exception.php';
 84            throw new Zend_Filter_Exception('Invalid options argument provided to filter');
 85        }
 86
 87        if (array_key_exists('compression', $options)) {
 88            $this->setCompression($options['compression']);
 89            unset($options['compress']);
 90        }
 91
 92        $this->setEncryption($options);
 93    }
 94
 95    /**
 96     * Returns the set encryption options
 97     *
 98     * @return array
 99     */
100    public function getEncryption()
101    {
102        return $this->_encryption;
103    }
104
105    /**
106     * Sets new encryption options
107     *
108     * @param  string|array $options Encryption options
109     * @return Zend_Filter_File_Encryption
110     */
111    public function setEncryption($options)
112    {
113        if (is_string($options)) {
114            $options = array('key' => $options);
115        }
116
117        if (!is_array($options)) {
118            require_once 'Zend/Filter/Exception.php';
119            throw new Zend_Filter_Exception('Invalid options argument provided to filter');
120        }
121
122        $options = $options + $this->getEncryption();
123        $algorithms = mcrypt_list_algorithms($options['algorithm_directory']);
124        if (!in_array($options['algorithm'], $algorithms)) {
125            require_once 'Zend/Filter/Exception.php';
126            throw new Zend_Filter_Exception("The algorithm '{$options['algorithm']}' is not supported");
127        }
128
129        $modes = mcrypt_list_modes($options['mode_directory']);
130        if (!in_array($options['mode'], $modes)) {
131            require_once 'Zend/Filter/Exception.php';
132            throw new Zend_Filter_Exception("The mode '{$options['mode']}' is not supported");
133        }
134
135        if (!mcrypt_module_self_test($options['algorithm'], $options['algorithm_directory'])) {
136            require_once 'Zend/Filter/Exception.php';
137            throw new Zend_Filter_Exception('The given algorithm can not be used due an internal mcrypt problem');
138        }
139
140        if (!isset($options['vector'])) {
141            $options['vector'] = null;
142        }
143
144        $this->_encryption = $options;
145        $this->setVector($options['vector']);
146
147        return $this;
148    }
149
150    /**
151     * Returns the set vector
152     *
153     * @return string
154     */
155    public function getVector()
156    {
157        return $this->_encryption['vector'];
158    }
159
160    /**
161     * Sets the initialization vector
162     *
163     * @param string $vector (Optional) Vector to set
164     * @return Zend_Filter_Encrypt_Mcrypt
165     */
166    public function setVector($vector = null)
167    {
168        $cipher = $this->_openCipher();
169        $size   = mcrypt_enc_get_iv_size($cipher);
170        if (empty($vector)) {
171            $this->_srand();
172            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && version_compare(PHP_VERSION, '5.3.0', '<')) {
173                $method = MCRYPT_RAND;
174            } else {
175                if (file_exists('/dev/urandom') || (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')) {
176                    $method = MCRYPT_DEV_URANDOM;
177                } elseif (file_exists('/dev/random')) {
178                    $method = MCRYPT_DEV_RANDOM;
179                } else {
180                    $method = MCRYPT_RAND;
181                }
182            }
183            $vector = mcrypt_create_iv($size, $method);
184        } else if (strlen($vector) != $size) {
185            require_once 'Zend/Filter/Exception.php';
186            throw new Zend_Filter_Exception('The given vector has a wrong size for the set algorithm');
187        }
188
189        $this->_encryption['vector'] = $vector;
190        $this->_closeCipher($cipher);
191
192        return $this;
193    }
194
195    /**
196     * Returns the compression
197     *
198     * @return array
199     */
200    public function getCompression()
201    {
202        return $this->_compression;
203    }
204
205    /**
206     * Sets a internal compression for values to encrypt
207     *
208     * @param string|array $compression
209     * @return Zend_Filter_Encrypt_Mcrypt
210     */
211    public function setCompression($compression)
212    {
213        if (is_string($this->_compression)) {
214            $compression = array('adapter' => $compression);
215        }
216
217        $this->_compression = $compression;
218        return $this;
219    }
220
221    /**
222     * Defined by Zend_Filter_Interface
223     *
224     * Encrypts $value with the defined settings
225     *
226     * @param  string $value The content to encrypt
227     * @return string The encrypted content
228     */
229    public function encrypt($value)
230    {
231        // compress prior to encryption
232        if (!empty($this->_compression)) {
233            require_once 'Zend/Filter/Compress.php';
234            $compress = new Zend_Filter_Compress($this->_compression);
235            $value    = $compress->filter($value);
236        }
237
238        $cipher  = $this->_openCipher();
239        $this->_initCipher($cipher);
240        $encrypted = mcrypt_generic($cipher, $value);
241        mcrypt_generic_deinit($cipher);
242        $this->_closeCipher($cipher);
243
244        return $encrypted;
245    }
246
247    /**
248     * Defined by Zend_Filter_Interface
249     *
250     * Decrypts $value with the defined settings
251     *
252     * @param  string $value Content to decrypt
253     * @return string The decrypted content
254     */
255    public function decrypt($value)
256    {
257        $cipher = $this->_openCipher();
258        $this->_initCipher($cipher);
259        $decrypted = mdecrypt_generic($cipher, $value);
260        mcrypt_generic_deinit($cipher);
261        $this->_closeCipher($cipher);
262
263        // decompress after decryption
264        if (!empty($this->_compression)) {
265            require_once 'Zend/Filter/Decompress.php';
266            $decompress = new Zend_Filter_Decompress($this->_compression);
267            $decrypted  = $decompress->filter($decrypted);
268        }
269
270        return $decrypted;
271    }
272
273    /**
274     * Returns the adapter name
275     *
276     * @return string
277     */
278    public function toString()
279    {
280        return 'Mcrypt';
281    }
282
283    /**
284     * Open a cipher
285     *
286     * @throws Zend_Filter_Exception When the cipher can not be opened
287     * @return resource Returns the opened cipher
288     */
289    protected function _openCipher()
290    {
291        $cipher = mcrypt_module_open(
292            $this->_encryption['algorithm'],
293            $this->_encryption['algorithm_directory'],
294            $this->_encryption['mode'],
295            $this->_encryption['mode_directory']);
296
297        if ($cipher === false) {
298            require_once 'Zend/Filter/Exception.php';
299            throw new Zend_Filter_Exception('Mcrypt can not be opened with your settings');
300        }
301
302        return $cipher;
303    }
304
305    /**
306     * Close a cipher
307     *
308     * @param  resource $cipher Cipher to close
309     * @return Zend_Filter_Encrypt_Mcrypt
310     */
311    protected function _closeCipher($cipher)
312    {
313        mcrypt_module_close($cipher);
314
315        return $this;
316    }
317
318    /**
319     * Initialises the cipher with the set key
320     *
321     * @param  resource $cipher
322     * @throws
323     * @return resource
324     */
325    protected function _initCipher($cipher)
326    {
327        $key = $this->_encryption['key'];
328
329        $keysizes = mcrypt_enc_get_supported_key_sizes($cipher);
330        if (empty($keysizes) || ($this->_encryption['salt'] == true)) {
331            $this->_srand();
332            $keysize = mcrypt_enc_get_key_size($cipher);
333            $key     = substr(md5($key), 0, $keysize);
334        } else if (!in_array(strlen($key), $keysizes)) {
335            require_once 'Zend/Filter/Exception.php';
336            throw new Zend_Filter_Exception('The given key has a wrong size for the set algorithm');
337        }
338
339        $result = mcrypt_generic_init($cipher, $key, $this->_encryption['vector']);
340        if ($result < 0) {
341            require_once 'Zend/Filter/Exception.php';
342            throw new Zend_Filter_Exception('Mcrypt could not be initialize with the given setting');
343        }
344
345        return $this;
346    }
347
348    /**
349     * _srand() interception
350     *
351     * @see ZF-8742
352     */
353    protected function _srand()
354    {
355        if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
356            return;
357        }
358
359        if (!self::$_srandCalled) {
360            srand((double) microtime() * 1000000);
361            self::$_srandCalled = true;
362        }
363    }
364}