Hi,为确保您的账号安全,请大家修改登陆密码为包含大小写字母、标点、数字的复合密码,不要使用过于简单的登陆密码。
您当前的位置:首页 :: PHP

PHP常用对称加密算法类

时间:2016-05-19 15:24:23  来源:  作者:

PHP常用对称加密算法类

<?php
/**
 * 常用对称加密算法类
 * 支持密钥:64/128/256 bit(字节长度8/16/32)
 * 支持算法:DES/AES(根据密钥长度自动匹配使用:DES:64bit AES:128/256bit)
 * 支持模式:CBC/ECB/OFB/CFB
 * 密文编码:base64字符串/十六进制字符串/二进制字符串流
 * 填充方式: PKCS5Padding(DES)
 */
class Mcrypt {

    private $mcrypt;
    private $key;
    private $mode;
    private $iv;
    private $blocksize;
    static $instance = null;

    /**
     * 初始化对象
     */
    public static function init($key, $iv = 'off', $mode = 'cbc') {
        if (empty($mode)) {
            $mode = MCRYPT_MODE_CBC;
        }
        if (self::$instance == null) {
            self::$instance = new self($key, $mode, $iv);
        }
        return self::$instance;
    }

    /**
     * 构造函数
     * @param string $key 密钥
     * @param string $mode 模式
     * @param string $iv 向量(off:不使用/auto:自动/其他:指定值,长度同密钥)
     */
    public function __construct($key, $mode = 'cbc', $iv = 'off') {
        switch (strlen($key)) {
            case 8:
                $this->mcrypt = MCRYPT_DES;
                break;
            case 16:
                $this->mcrypt = MCRYPT_RIJNDAEL_128;
                $key = $this->_getHashKey($key);
                break;
            case 32:
                $this->mcrypt = MCRYPT_RIJNDAEL_256;
                break;
            default:
                die('Key size must be 8/16/32');
        }

        $this->key = $key;

        switch (strtolower($mode)) {
            case 'ofb':
                $this->mode = MCRYPT_MODE_OFB;
                if ($iv == 'off')
                    die('ofb must give a iv'); // ofb必须有向量
                break;
            case 'cfb':
                $this->mode = MCRYPT_MODE_CFB;
                if ($iv == 'off')
                    die('cfb must give a iv'); // cfb必须有向量
                break;
            case 'ecb':
                $this->mode = MCRYPT_MODE_ECB;
                $iv = 'off'; // ecb不需要向量
                break;
            case 'cbc':
            default:
                $this->mode = MCRYPT_MODE_CBC;
        }

        switch (strtolower($iv)) {
            case 'off':
                $this->iv = null;
                break;
            case 'auto':
                $source = PHP_OS == 'WINNT' ? MCRYPT_RAND : MCRYPT_DEV_RANDOM;
                $this->iv = mcrypt_create_iv(mcrypt_get_block_size($this->mcrypt, $this->mode), $source);
                break;
            default:
                $this->iv = $this->_hexToStr($iv);
        }
    }

    /**
     * 加密字符串
     * @param string $str 明文
     * @param string $code 密文编码(base64/hex/bin)
     * @return string 密文
     */
    public function encrypt($str, $code = 'base64') {
        if ($this->mcrypt == MCRYPT_DES || $this->mcrypt == MCRYPT_RIJNDAEL_128) {
            $str = $this->_pkcs5Pad($str);
        }

        if (isset($this->iv)) {
            $result = mcrypt_encrypt($this->mcrypt, $this->key, $str, $this->mode, $this->iv);
            //$result = $this->_encryptAES($str);
        } else {
            @$result = mcrypt_encrypt($this->mcrypt, $this->key, $str, $this->mode);
        }
        switch ($code) {
            case 'base64':
                $ret = base64_encode($result);
                break;
            case 'hex':
                $ret = bin2hex($result);
                break;
            case 'bin':
            default:
                $ret = $result;
        }
        return $ret;
    }

    /**
     * 解密字符串
     * @param string $str 密文
     * @param string $code 密文编码(base64/hex/bin)
     * @return string 明文
     */
    public function decrypt($str, $code = 'base64') {
        $ret = false;
        switch ($code) {
            case 'base64':
                $str = base64_decode($str);
                break;
            case 'hex':
                $str = $this->_hex2bin($str);
                break;
            case 'bin':
            default:
        }

        if ($str !== false) {
            if (isset($this->iv))
                $ret = mcrypt_decrypt($this->mcrypt, $this->key, $str, $this->mode, $this->iv);
            else
                @$ret = mcrypt_decrypt($this->mcrypt, $this->key, $str, $this->mode);
            if ($this->mcrypt == MCRYPT_DES || $this->mcrypt == MCRYPT_RIJNDAEL_128)
                $ret = $this->_pkcs5Unpad($ret);
            $ret = trim($ret);
        }
        return $ret;
    }

    /**
     * 获取向量值
     * @param string 向量值编码(base64/hex/bin)
     * @return string 向量值
     */
    private function getIv($code = 'base64') {
        switch ($code) {
            case 'base64':
                $ret = base64_encode($this->iv);
                break;
            case 'hex':
                $ret = bin2hex($this->iv);
                break;
            case 'bin':
            default:
                $ret = $this->iv;
        }
        return $ret;
    }
    private function _pkcs5Pad($text) {
        $this->blocksize = mcrypt_get_block_size($this->mcrypt, $this->mode);
        $pad = $this->blocksize - (strlen($text) % $this->blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    private function _pkcs5Unpad($text) {
        $pad = ord($text{strlen($text) - 1});
        if ($pad > strlen($text))
            return false;
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
            return false;
        return substr($text, 0, -1 * $pad);
    }

    private function _hex2bin($hex = false) {
        return $hex !== false && preg_match('/^[0-9a-fA-F]+$/i', $hex) ? pack('H*', $hex) : false;
    }

    private function _getHashKey($key, $algo = 'sha256') {
        return hash($algo, $key, true);
    }

    private function _hexToStr($hex) {
        $string = '';
        for ($i = 0; $i < strlen($hex) - 1; $i+=2) {
            $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
        }
        return $string;
    }

}

 

举报
收藏0次 / 评论0
评论(0)
还可以输入 2000 个字符
还可以输入 2000 个字符
取消回复
举报×

还可以输入 264 字符

收藏(0)×