【问题标题】:php error: The Encrypt library requires the Mcrypt extension in codeigniterphp 错误:加密库需要 codeigniter 中的 Mcrypt 扩展
【发布时间】:2016-06-18 07:20:53
【问题描述】:

我有一个登录和注册表单,并使用加密库来加密密码。我正在为我的服务器使用 Xampp,我的系统工作正常。

密码加密代码:

$this->encrypt->encode('my password'); 

添加加密库

 $autoload['libraries'] = array('encrypt');

并在配置中设置密钥:

$config['encryption_key'] = 'nmsc encrypt secret key';

我的代码在 Windows 中使用 xampp 服务器运行良好,但是当我尝试将我的网站上传到 ubuntu 服务器时出现错误提示

加密库需要 Mcrypt 扩展

如何解决这个问题?参考本指南https://www.codeigniter.com/user_guide/libraries/encryption.html,但我不知道如何安装该 mcrypt。我的网站需要从 ubuntu 服务器运行。如何安装或解决该问题?

【问题讨论】:

  • 您不应该使用 mcrypt,它是废弃软件,多年未更新,不支持标准填充(PKCS#5 或 PKCS#7),并且使用空填充,这将无法与二进制文件正常工作数据。请考虑使用defuseRNCryptor-php 以获得完整的安全解决方案。
  • CodeIgniter 3 提供了一个不同的加密类,即使不是所有的事情都正确。如果您可以访问 codeigniter 3,请使用它。
  • 密码必须散列,而不是加密。使用secure.php.net/password
  • 这个答案对我有用。 stackoverflow.com/a/54334312/8889610

标签: php codeigniter encryption mcrypt


【解决方案1】:

最佳解决方案是(仅适用于 CI 3 及更高版本):

改变

 $this->load->library('encrypt');

 $this->load->library('encryption');

【讨论】:

  • 请同时注明文件名
  • 它是否适用于 CI4?
【解决方案2】:

你应该安装 PHP mcrypt 模块;

sudo apt-get install php5-mcrypt
sudo php5enmod mcrypt

通常你会很好;)

【讨论】:

  • 我没有使用 ubuntu 来开发我的项目,有没有办法使用 xampp 从 Windows 安装 php5-mcrypt?我的学校正在使用 ubuntu 服务器。
  • 我不是windows用户,但我发现这个链接可能对你有帮助myoddweb.com/2010/11/18/install-mcrypt-for-php-on-windows
  • 但我必须建议您切换到 Linux。 ^^
  • 执行此操作后不要忘记重新加载 apache:service apache2 reload
【解决方案3】:

将此代码保存到库/Encrypt.php

它一定是工作!

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package     CodeIgniter
 * @author      ExpressionEngine Dev Team
 * @copyright   Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license     http://codeigniter.com/user_guide/license.html
 * @link        http://codeigniter.com
 * @since       Version 1.0
 * @filesource
 */
// ------------------------------------------------------------------------
/**
 * CodeIgniter Encryption Class
 *
 * Provides two-way keyed encoding using XOR Hashing and Mcrypt
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Libraries
 * @author      ExpressionEngine Dev Team
 * @link        http://codeigniter.com/user_guide/libraries/encryption.html
 */
class CI_Encrypt {
    var $CI;
    var $encryption_key = '';
    var $_hash_type = 'sha1';
    var $_mcrypt_exists = FALSE;
    var $_mcrypt_cipher;
    var $_mcrypt_mode;
    /**
     * Constructor
     *
     * Simply determines whether the mcrypt library exists.
     *
     */
    public function __construct()
    {
        $this->CI =& get_instance();
        $this->_mcrypt_exists = ( ! function_exists('mcrypt_encrypt')) ? FALSE : TRUE;
        log_message('debug', "Encrypt Class Initialized");
    }
    // --------------------------------------------------------------------
    /**
     * Fetch the encryption key
     *
     * Returns it as MD5 in order to have an exact-length 128 bit key.
     * Mcrypt is sensitive to keys that are not the correct length
     *
     * @access  public
     * @param   string
     * @return  string
     */
    function get_key($key = '')
    {
        if ($key == '')
        {
            if ($this->encryption_key != '')
            {
                return $this->encryption_key;
            }
            $CI =& get_instance();
            $key = $CI->config->item('encryption_key');
            if ($key == FALSE)
            {
                show_error('In order to use the encryption class requires that you set an encryption key in your config file.');
            }
        }
        return md5($key);
    }
    // --------------------------------------------------------------------
    /**
     * Set the encryption key
     *
     * @access  public
     * @param   string
     * @return  void
     */
    function set_key($key = '')
    {
        $this->encryption_key = $key;
    }
    // --------------------------------------------------------------------
    /**
     * Encode
     *
     * Encodes the message string using bitwise XOR encoding.
     * The key is combined with a random hash, and then it
     * too gets converted using XOR. The whole thing is then run
     * through mcrypt (if supported) using the randomized key.
     * The end result is a double-encrypted message string
     * that is randomized with each call to this function,
     * even if the supplied message and key are the same.
     *
     * @access  public
     * @param   string  the string to encode
     * @param   string  the key
     * @return  string
     */
    function encode($string, $key = '')
    {
        $key = $this->get_key($key);
        if ($this->_mcrypt_exists === TRUE)
        {
            $enc = $this->mcrypt_encode($string, $key);
        }
        else
        {
            $enc = $this->_xor_encode($string, $key);
        }
        return base64_encode($enc);
    }
    // --------------------------------------------------------------------
    /**
     * Decode
     *
     * Reverses the above process
     *
     * @access  public
     * @param   string
     * @param   string
     * @return  string
     */
    function decode($string, $key = '')
    {
        $key = $this->get_key($key);
        if (preg_match('/[^a-zA-Z0-9\/\+=]/', $string))
        {
            return FALSE;
        }
        $dec = base64_decode($string);
        if ($this->_mcrypt_exists === TRUE)
        {
            if (($dec = $this->mcrypt_decode($dec, $key)) === FALSE)
            {
                return FALSE;
            }
        }
        else
        {
            $dec = $this->_xor_decode($dec, $key);
        }
        return $dec;
    }
    // --------------------------------------------------------------------
    /**
     * Encode from Legacy
     *
     * Takes an encoded string from the original Encryption class algorithms and
     * returns a newly encoded string using the improved method added in 2.0.0
     * This allows for backwards compatibility and a method to transition to the
     * new encryption algorithms.
     *
     * For more details, see http://codeigniter.com/user_guide/installation/upgrade_200.html#encryption
     *
     * @access  public
     * @param   string
     * @param   int     (mcrypt mode constant)
     * @param   string
     * @return  string
     */
    function encode_from_legacy($string, $legacy_mode = MCRYPT_MODE_ECB, $key = '')
    {
        if ($this->_mcrypt_exists === FALSE)
        {
            log_message('error', 'Encoding from legacy is available only when Mcrypt is in use.');
            return FALSE;
        }
        // decode it first
        // set mode temporarily to what it was when string was encoded with the legacy
        // algorithm - typically MCRYPT_MODE_ECB
        $current_mode = $this->_get_mode();
        $this->set_mode($legacy_mode);
        $key = $this->get_key($key);
        if (preg_match('/[^a-zA-Z0-9\/\+=]/', $string))
        {
            return FALSE;
        }
        $dec = base64_decode($string);
        if (($dec = $this->mcrypt_decode($dec, $key)) === FALSE)
        {
            return FALSE;
        }
        $dec = $this->_xor_decode($dec, $key);
        // set the mcrypt mode back to what it should be, typically MCRYPT_MODE_CBC
        $this->set_mode($current_mode);
        // and re-encode
        return base64_encode($this->mcrypt_encode($dec, $key));
    }
    // --------------------------------------------------------------------
    /**
     * XOR Encode
     *
     * Takes a plain-text string and key as input and generates an
     * encoded bit-string using XOR
     *
     * @access  private
     * @param   string
     * @param   string
     * @return  string
     */
    function _xor_encode($string, $key)
    {
        $rand = '';
        while (strlen($rand) < 32)
        {
            $rand .= mt_rand(0, mt_getrandmax());
        }
        $rand = $this->hash($rand);
        $enc = '';
        for ($i = 0; $i < strlen($string); $i++)
        {
            $enc .= substr($rand, ($i % strlen($rand)), 1).(substr($rand, ($i % strlen($rand)), 1) ^ substr($string, $i, 1));
        }
        return $this->_xor_merge($enc, $key);
    }
    // --------------------------------------------------------------------
    /**
     * XOR Decode
     *
     * Takes an encoded string and key as input and generates the
     * plain-text original message
     *
     * @access  private
     * @param   string
     * @param   string
     * @return  string
     */
    function _xor_decode($string, $key)
    {
        $string = $this->_xor_merge($string, $key);
        $dec = '';
        for ($i = 0; $i < strlen($string); $i++)
        {
            $dec .= (substr($string, $i++, 1) ^ substr($string, $i, 1));
        }
        return $dec;
    }
    // --------------------------------------------------------------------
    /**
     * XOR key + string Combiner
     *
     * Takes a string and key as input and computes the difference using XOR
     *
     * @access  private
     * @param   string
     * @param   string
     * @return  string
     */
    function _xor_merge($string, $key)
    {
        $hash = $this->hash($key);
        $str = '';
        for ($i = 0; $i < strlen($string); $i++)
        {
            $str .= substr($string, $i, 1) ^ substr($hash, ($i % strlen($hash)), 1);
        }
        return $str;
    }
    // --------------------------------------------------------------------
    /**
     * Encrypt using Mcrypt
     *
     * @access  public
     * @param   string
     * @param   string
     * @return  string
     */
    function mcrypt_encode($data, $key)
    {
        $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
        $init_vect = mcrypt_create_iv($init_size, MCRYPT_RAND);
        return $this->_add_cipher_noise($init_vect.mcrypt_encrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), $key);
    }
    // --------------------------------------------------------------------
    /**
     * Decrypt using Mcrypt
     *
     * @access  public
     * @param   string
     * @param   string
     * @return  string
     */
    function mcrypt_decode($data, $key)
    {
        $data = $this->_remove_cipher_noise($data, $key);
        $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
        if ($init_size > strlen($data))
        {
            return FALSE;
        }
        $init_vect = substr($data, 0, $init_size);
        $data = substr($data, $init_size);
        return rtrim(mcrypt_decrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), "\0");
    }
    // --------------------------------------------------------------------
    /**
     * Adds permuted noise to the IV + encrypted data to protect
     * against Man-in-the-middle attacks on CBC mode ciphers
     * http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
     *
     * Function description
     *
     * @access  private
     * @param   string
     * @param   string
     * @return  string
     */
    function _add_cipher_noise($data, $key)
    {
        $keyhash = $this->hash($key);
        $keylen = strlen($keyhash);
        $str = '';
        for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
        {
            if ($j >= $keylen)
            {
                $j = 0;
            }
            $str .= chr((ord($data[$i]) + ord($keyhash[$j])) % 256);
        }
        return $str;
    }
    // --------------------------------------------------------------------
    /**
     * Removes permuted noise from the IV + encrypted data, reversing
     * _add_cipher_noise()
     *
     * Function description
     *
     * @access  public
     * @param   type
     * @return  type
     */
    function _remove_cipher_noise($data, $key)
    {
        $keyhash = $this->hash($key);
        $keylen = strlen($keyhash);
        $str = '';
        for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
        {
            if ($j >= $keylen)
            {
                $j = 0;
            }
            $temp = ord($data[$i]) - ord($keyhash[$j]);
            if ($temp < 0)
            {
                $temp = $temp + 256;
            }
            $str .= chr($temp);
        }
        return $str;
    }
    // --------------------------------------------------------------------
    /**
     * Set the Mcrypt Cipher
     *
     * @access  public
     * @param   constant
     * @return  string
     */
    function set_cipher($cipher)
    {
        $this->_mcrypt_cipher = $cipher;
    }
    // --------------------------------------------------------------------
    /**
     * Set the Mcrypt Mode
     *
     * @access  public
     * @param   constant
     * @return  string
     */
    function set_mode($mode)
    {
        $this->_mcrypt_mode = $mode;
    }
    // --------------------------------------------------------------------
    /**
     * Get Mcrypt cipher Value
     *
     * @access  private
     * @return  string
     */
    function _get_cipher()
    {
        if ($this->_mcrypt_cipher == '')
        {
            $this->_mcrypt_cipher = MCRYPT_RIJNDAEL_256;
        }
        return $this->_mcrypt_cipher;
    }
    // --------------------------------------------------------------------
    /**
     * Get Mcrypt Mode Value
     *
     * @access  private
     * @return  string
     */
    function _get_mode()
    {
        if ($this->_mcrypt_mode == '')
        {
            $this->_mcrypt_mode = MCRYPT_MODE_CBC;
        }
        return $this->_mcrypt_mode;
    }
    // --------------------------------------------------------------------
    /**
     * Set the Hash type
     *
     * @access  public
     * @param   string
     * @return  string
     */
    function set_hash($type = 'sha1')
    {
        $this->_hash_type = ($type != 'sha1' AND $type != 'md5') ? 'sha1' : $type;
    }
    // --------------------------------------------------------------------
    /**
     * Hash encode a string
     *
     * @access  public
     * @param   string
     * @return  string
     */
    function hash($str)
    {
        return ($this->_hash_type == 'sha1') ? $this->sha1($str) : md5($str);
    }
    // --------------------------------------------------------------------
    /**
     * Generate an SHA1 Hash
     *
     * @access  public
     * @param   string
     * @return  string
     */
    function sha1($str)
    {
        if ( ! function_exists('sha1'))
        {
            if ( ! function_exists('mhash'))
            {
                require_once(BASEPATH.'libraries/Sha1.php');
                $SH = new CI_SHA;
                return $SH->generate($str);
            }
            else
            {
                return bin2hex(mhash(MHASH_SHA1, $str));
            }
        }
        else
        {
            return sha1($str);
        }
    }
}
// END CI_Encrypt class
/* End of file Encrypt.php */

【讨论】:

  • 谢谢,我在 godady 服务器上的代码中出现错误,但这个解决方案有效。
【解决方案4】:

我收到此错误是因为我已从 XAMPP(php5) 切换到 XAMPP(php7), 为此,我在这里用新文件替换了旧的 CI->system->libraries->encrypt.php:encrypt.php,它起作用了。

在这个新文件中,我们使用下面的代码检查 __construct 函数中是否支持 mcrypt_encrypt

   $this->_mcrypt_exists = ( ! function_exists('mcrypt_encrypt')) ? FALSE : TRUE;

基于此,我们在 mcrypt_encode 和 _xor_encode 之间使用不同的函数。

要知道,如果你在 __construct 函数中看到这个旧文件,你会看到实际的错误检查

    if (($this->_mcrypt_exists = function_exists('mcrypt_encrypt')) === FALSE)
    {
        show_error('The Encrypt library requires the Mcrypt extension.');
    }

它对我有用。

【讨论】:

  • 这行得通,因为它修复了像 Codeigniter 2 这样的旧系统中为 PHP 5.x 设计的错误 PHP 函数
  • 也为我工作,谢谢。
【解决方案5】:

对我有用的解决方案是

之前:

$autoload['libraries'] = array('database','session','upload','form_validation','encrypt','pagination');

之后:

$autoload['libraries'] = array('database','session','upload','form_validation','pagination');

我刚刚从自动加载库中删除了加密库。

【讨论】:

    【解决方案6】:

    对于 php 7.2 版本和 Ubuntu 系统,以下命令适用于我 -

    sudo apt-get -y install gcc make autoconf libc-dev pkg-config
    sudo apt-get -y install php7.2-dev
    sudo apt-get -y install libmcrypt-dev
    pecl install mcrypt-1.0.1
    

    然后它会显示一条消息“您应该在 php.ini 中添加 mcrypt 扩展”

    extension=mcrypt.so
    

    然后重启apache服务器

    service apache2 restart
    or
    systemctl restart apache2
    

    【讨论】:

      【解决方案7】:

      听起来你需要更新你的 php 版本。

      http://php.net/manual/en/mcrypt.requirements.php
      

      【讨论】:

        【解决方案8】:

        打开你的:/etc/php5/apache2/php.ini
        示例:sudo gedit /etc/php5/apache2/php.ini
        在第 1728 行,输入以下代码:

        extension=mcrypt.so
        

        然后重新启动您的 Apache。

        【讨论】:

        • 对我没有任何改善
        【解决方案9】:

        我遇到了类似的问题,所以我将此代码放入/system/libraris/Encrypt.php,现在它运行正常。

        <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
        /**
         * CodeIgniter
         *
         * An open source application development framework for PHP 5.1.6 or newer
         *
         * @package     CodeIgniter
         * @author      ExpressionEngine Dev Team
         * @copyright   Copyright (c) 2008 - 2011, EllisLab, Inc.
         * @license     http://codeigniter.com/user_guide/license.html
         * @link        http://codeigniter.com
         * @since       Version 1.0
         * @filesource
         */
        // ------------------------------------------------------------------------
        /**
         * CodeIgniter Encryption Class
         *
         * Provides two-way keyed encoding using XOR Hashing and Mcrypt
         *
         * @package     CodeIgniter
         * @subpackage  Libraries
         * @category    Libraries
         * @author      ExpressionEngine Dev Team
         * @link        http://codeigniter.com/user_guide/libraries/encryption.html
         */
        class CI_Encrypt {
            var $CI;
            var $encryption_key = '';
            var $_hash_type = 'sha1';
            var $_mcrypt_exists = FALSE;
            var $_mcrypt_cipher;
            var $_mcrypt_mode;
            /**
             * Constructor
             *
             * Simply determines whether the mcrypt library exists.
             *
             */
            public function __construct()
            {
                $this->CI =& get_instance();
                $this->_mcrypt_exists = ( ! function_exists('mcrypt_encrypt')) ? FALSE : TRUE;
                log_message('debug', "Encrypt Class Initialized");
            }
            // --------------------------------------------------------------------
            /**
             * Fetch the encryption key
             *
             * Returns it as MD5 in order to have an exact-length 128 bit key.
             * Mcrypt is sensitive to keys that are not the correct length
             *
             * @access  public
             * @param   string
             * @return  string
             */
            function get_key($key = '')
            {
                if ($key == '')
                {
                    if ($this->encryption_key != '')
                    {
                        return $this->encryption_key;
                    }
                    $CI =& get_instance();
                    $key = $CI->config->item('encryption_key');
                    if ($key == FALSE)
                    {
                        show_error('In order to use the encryption class requires that you set an encryption key in your config file.');
                    }
                }
                return md5($key);
            }
            // --------------------------------------------------------------------
            /**
             * Set the encryption key
             *
             * @access  public
             * @param   string
             * @return  void
             */
            function set_key($key = '')
            {
                $this->encryption_key = $key;
            }
            // --------------------------------------------------------------------
            /**
             * Encode
             *
             * Encodes the message string using bitwise XOR encoding.
             * The key is combined with a random hash, and then it
             * too gets converted using XOR. The whole thing is then run
             * through mcrypt (if supported) using the randomized key.
             * The end result is a double-encrypted message string
             * that is randomized with each call to this function,
             * even if the supplied message and key are the same.
             *
             * @access  public
             * @param   string  the string to encode
             * @param   string  the key
             * @return  string
             */
            function encode($string, $key = '')
            {
                $key = $this->get_key($key);
                if ($this->_mcrypt_exists === TRUE)
                {
                    $enc = $this->mcrypt_encode($string, $key);
                }
                else
                {
                    $enc = $this->_xor_encode($string, $key);
                }
                return base64_encode($enc);
            }
            // --------------------------------------------------------------------
            /**
             * Decode
             *
             * Reverses the above process
             *
             * @access  public
             * @param   string
             * @param   string
             * @return  string
             */
            function decode($string, $key = '')
            {
                $key = $this->get_key($key);
                if (preg_match('/[^a-zA-Z0-9\/\+=]/', $string))
                {
                    return FALSE;
                }
                $dec = base64_decode($string);
                if ($this->_mcrypt_exists === TRUE)
                {
                    if (($dec = $this->mcrypt_decode($dec, $key)) === FALSE)
                    {
                        return FALSE;
                    }
                }
                else
                {
                    $dec = $this->_xor_decode($dec, $key);
                }
                return $dec;
            }
            // --------------------------------------------------------------------
            /**
             * Encode from Legacy
             *
             * Takes an encoded string from the original Encryption class algorithms and
             * returns a newly encoded string using the improved method added in 2.0.0
             * This allows for backwards compatibility and a method to transition to the
             * new encryption algorithms.
             *
             * For more details, see http://codeigniter.com/user_guide/installation/upgrade_200.html#encryption
             *
             * @access  public
             * @param   string
             * @param   int     (mcrypt mode constant)
             * @param   string
             * @return  string
             */
            function encode_from_legacy($string, $legacy_mode = MCRYPT_MODE_ECB, $key = '')
            {
                if ($this->_mcrypt_exists === FALSE)
                {
                    log_message('error', 'Encoding from legacy is available only when Mcrypt is in use.');
                    return FALSE;
                }
                // decode it first
                // set mode temporarily to what it was when string was encoded with the legacy
                // algorithm - typically MCRYPT_MODE_ECB
                $current_mode = $this->_get_mode();
                $this->set_mode($legacy_mode);
                $key = $this->get_key($key);
                if (preg_match('/[^a-zA-Z0-9\/\+=]/', $string))
                {
                    return FALSE;
                }
                $dec = base64_decode($string);
                if (($dec = $this->mcrypt_decode($dec, $key)) === FALSE)
                {
                    return FALSE;
                }
                $dec = $this->_xor_decode($dec, $key);
                // set the mcrypt mode back to what it should be, typically MCRYPT_MODE_CBC
                $this->set_mode($current_mode);
                // and re-encode
                return base64_encode($this->mcrypt_encode($dec, $key));
            }
            // --------------------------------------------------------------------
            /**
             * XOR Encode
             *
             * Takes a plain-text string and key as input and generates an
             * encoded bit-string using XOR
             *
             * @access  private
             * @param   string
             * @param   string
             * @return  string
             */
            function _xor_encode($string, $key)
            {
                $rand = '';
                while (strlen($rand) < 32)
                {
                    $rand .= mt_rand(0, mt_getrandmax());
                }
                $rand = $this->hash($rand);
                $enc = '';
                for ($i = 0; $i < strlen($string); $i++)
                {
                    $enc .= substr($rand, ($i % strlen($rand)), 1).(substr($rand, ($i % strlen($rand)), 1) ^ substr($string, $i, 1));
                }
                return $this->_xor_merge($enc, $key);
            }
            // --------------------------------------------------------------------
            /**
             * XOR Decode
             *
             * Takes an encoded string and key as input and generates the
             * plain-text original message
             *
             * @access  private
             * @param   string
             * @param   string
             * @return  string
             */
            function _xor_decode($string, $key)
            {
                $string = $this->_xor_merge($string, $key);
                $dec = '';
                for ($i = 0; $i < strlen($string); $i++)
                {
                    $dec .= (substr($string, $i++, 1) ^ substr($string, $i, 1));
                }
                return $dec;
            }
            // --------------------------------------------------------------------
            /**
             * XOR key + string Combiner
             *
             * Takes a string and key as input and computes the difference using XOR
             *
             * @access  private
             * @param   string
             * @param   string
             * @return  string
             */
            function _xor_merge($string, $key)
            {
                $hash = $this->hash($key);
                $str = '';
                for ($i = 0; $i < strlen($string); $i++)
                {
                    $str .= substr($string, $i, 1) ^ substr($hash, ($i % strlen($hash)), 1);
                }
                return $str;
            }
            // --------------------------------------------------------------------
            /**
             * Encrypt using Mcrypt
             *
             * @access  public
             * @param   string
             * @param   string
             * @return  string
             */
            function mcrypt_encode($data, $key)
            {
                $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
                $init_vect = mcrypt_create_iv($init_size, MCRYPT_RAND);
                return $this->_add_cipher_noise($init_vect.mcrypt_encrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), $key);
            }
            // --------------------------------------------------------------------
            /**
             * Decrypt using Mcrypt
             *
             * @access  public
             * @param   string
             * @param   string
             * @return  string
             */
            function mcrypt_decode($data, $key)
            {
                $data = $this->_remove_cipher_noise($data, $key);
                $init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
                if ($init_size > strlen($data))
                {
                    return FALSE;
                }
                $init_vect = substr($data, 0, $init_size);
                $data = substr($data, $init_size);
                return rtrim(mcrypt_decrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), "\0");
            }
            // --------------------------------------------------------------------
            /**
             * Adds permuted noise to the IV + encrypted data to protect
             * against Man-in-the-middle attacks on CBC mode ciphers
             * http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
             *
             * Function description
             *
             * @access  private
             * @param   string
             * @param   string
             * @return  string
             */
            function _add_cipher_noise($data, $key)
            {
                $keyhash = $this->hash($key);
                $keylen = strlen($keyhash);
                $str = '';
                for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
                {
                    if ($j >= $keylen)
                    {
                        $j = 0;
                    }
                    $str .= chr((ord($data[$i]) + ord($keyhash[$j])) % 256);
                }
                return $str;
            }
            // --------------------------------------------------------------------
            /**
             * Removes permuted noise from the IV + encrypted data, reversing
             * _add_cipher_noise()
             *
             * Function description
             *
             * @access  public
             * @param   type
             * @return  type
             */
            function _remove_cipher_noise($data, $key)
            {
                $keyhash = $this->hash($key);
                $keylen = strlen($keyhash);
                $str = '';
                for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
                {
                    if ($j >= $keylen)
                    {
                        $j = 0;
                    }
                    $temp = ord($data[$i]) - ord($keyhash[$j]);
                    if ($temp < 0)
                    {
                        $temp = $temp + 256;
                    }
                    $str .= chr($temp);
                }
                return $str;
            }
            // --------------------------------------------------------------------
            /**
             * Set the Mcrypt Cipher
             *
             * @access  public
             * @param   constant
             * @return  string
             */
            function set_cipher($cipher)
            {
                $this->_mcrypt_cipher = $cipher;
            }
            // --------------------------------------------------------------------
            /**
             * Set the Mcrypt Mode
             *
             * @access  public
             * @param   constant
             * @return  string
             */
            function set_mode($mode)
            {
                $this->_mcrypt_mode = $mode;
            }
            // --------------------------------------------------------------------
            /**
             * Get Mcrypt cipher Value
             *
             * @access  private
             * @return  string
             */
            function _get_cipher()
            {
                if ($this->_mcrypt_cipher == '')
                {
                    $this->_mcrypt_cipher = MCRYPT_RIJNDAEL_256;
                }
                return $this->_mcrypt_cipher;
            }
            // --------------------------------------------------------------------
            /**
             * Get Mcrypt Mode Value
             *
             * @access  private
             * @return  string
             */
            function _get_mode()
            {
                if ($this->_mcrypt_mode == '')
                {
                    $this->_mcrypt_mode = MCRYPT_MODE_CBC;
                }
                return $this->_mcrypt_mode;
            }
            // --------------------------------------------------------------------
            /**
             * Set the Hash type
             *
             * @access  public
             * @param   string
             * @return  string
             */
            function set_hash($type = 'sha1')
            {
                $this->_hash_type = ($type != 'sha1' AND $type != 'md5') ? 'sha1' : $type;
            }
            // --------------------------------------------------------------------
            /**
             * Hash encode a string
             *
             * @access  public
             * @param   string
             * @return  string
             */
            function hash($str)
            {
                return ($this->_hash_type == 'sha1') ? $this->sha1($str) : md5($str);
            }
            // --------------------------------------------------------------------
            /**
             * Generate an SHA1 Hash
             *
             * @access  public
             * @param   string
             * @return  string
             */
            function sha1($str)
            {
                if ( ! function_exists('sha1'))
                {
                    if ( ! function_exists('mhash'))
                    {
                        require_once(BASEPATH.'libraries/Sha1.php');
                        $SH = new CI_SHA;
                        return $SH->generate($str);
                    }
                    else
                    {
                        return bin2hex(mhash(MHASH_SHA1, $str));
                    }
                }
                else
                {
                    return sha1($str);
                }
            }
        }
        // END CI_Encrypt class
        /* End of file Encrypt.php */
        

        【讨论】:

          【解决方案10】:

          使用 php 7 及更高版本的 mcrypt 不需要手动加载,因此这两种解决方案都可以工作。

          1. $this-&gt;load-&gt;library('encrypt'); 改成 $this-&gt;load-&gt;library('encrypt');

          2. 只需从自动加载中删除加密

            $autoload['libraries'] = array('database','session','upload','form_validation','encrypt','pagination');

          改成

          $autoload['libraries'] = array('database','session','upload','form_validation','encrypt','pagination');

          【讨论】:

            猜你喜欢
            • 2019-01-19
            • 2014-09-26
            • 2017-05-11
            • 2018-11-05
            • 2017-09-15
            相关资源
            最近更新 更多