1<?php
2/**
3 * Copyright 2005-2008 Matthew Fonda <mfonda@php.net>
4 * Copyright 2008 Philippe Jausions <jausions@php.net>
5 * Copyright 2012-2016 Horde LLC (http://www.horde.org/)
6 *
7 * See the enclosed file COPYING for license information (LGPL). If you
8 * did not receive this file, see http://www.horde.org/licenses/lgpl21.
9 *
10 * @category  Horde
11 * @copyright 2005-2008 Matthew Fonda
12 * @copyright 2012-2016 Horde LLC
13 * @license   http://www.horde.org/licenses/lgpl21 LGPL 2.1
14 * @package   Crypt_Blowfish
15 */
16
17/**
18 * Mcrypt driver for blowfish encryption.
19 *
20 * @author    Matthew Fonda <mfonda@php.net>
21 * @author    Philippe Jausions <jausions@php.net>
22 * @author    Michael Slusarz <slusarz@horde.org>
23 * @category  Horde
24 * @copyright 2005-2008 Matthew Fonda
25 * @copyright 2012-2016 Horde LLC
26 * @license   http://www.horde.org/licenses/lgpl21 LGPL 2.1
27 * @package   Crypt_Blowfish
28 */
29class Horde_Crypt_Blowfish_Mcrypt extends Horde_Crypt_Blowfish_Base
30{
31    /**
32     * Mcrypt resource.
33     *
34     * @var resource
35     */
36    private $_mcrypt;
37
38    /**
39     */
40    public static function supported()
41    {
42        return PHP_VERSION_ID < 70100 && extension_loaded('mcrypt');
43    }
44
45    /**
46     */
47    public function __construct($cipher)
48    {
49        parent::__construct($cipher);
50
51        $this->_mcrypt = mcrypt_module_open(MCRYPT_BLOWFISH, '', $cipher, '');
52    }
53
54    /**
55     */
56    public function encrypt($text)
57    {
58        mcrypt_generic_init($this->_mcrypt, $this->key, empty($this->iv) ? str_repeat('0', Horde_Crypt_Blowfish::IV_LENGTH) : $this->iv);
59        $out = mcrypt_generic($this->_mcrypt, $this->_pad($text));
60        mcrypt_generic_deinit($this->_mcrypt);
61
62        return $out;
63    }
64
65    /**
66     */
67    public function decrypt($text)
68    {
69        mcrypt_generic_init($this->_mcrypt, $this->key, empty($this->iv) ? str_repeat('0', Horde_Crypt_Blowfish::IV_LENGTH) : $this->iv);
70        $out = mdecrypt_generic($this->_mcrypt, $this->_pad($text, true));
71        mcrypt_generic_deinit($this->_mcrypt);
72
73        return $this->_unpad($out);
74    }
75
76    /**
77     */
78    public function setIv($iv = null)
79    {
80        $this->iv = is_null($iv)
81            ? mcrypt_create_iv(Horde_Crypt_Blowfish::IV_LENGTH, MCRYPT_RAND)
82            : $iv;
83    }
84
85}
86