AES-128-ECB php兼容高低版本

class Aes {
    /**
     * 加密
     * @param $plain
     * @param $key
     * @return false|string
     */
    public static function encrypt($plain, $key)
    {
        if (trim($key) == '') {
            return false;
        }
        $key = self::_sha1prng($key);
        if(version_compare(PHP_VERSION,'7.1','>=')){
            $iv = '';
            $encrypted = openssl_encrypt($plain, 'AES-128-ECB', $key, OPENSSL_RAW_DATA, $iv);
        }else{
            $plain       = strval($plain);
            $block_size  = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
            $padded_data = self::_pkcs5_pad($plain, $block_size);
            $iv_size     = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
            $iv          = mcrypt_create_iv($iv_size, MCRYPT_RAND);
            $encrypted   = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $padded_data, MCRYPT_MODE_ECB, $iv);
        }
        return base64_encode($encrypted);
    }

    /**
     * aes解密
     * @param $cipher   密文
     * @param $key
     * @return false|string
     */
    public static function decrypt($cipher, $key)
    {
        if ( ! is_string($cipher) || trim($key) == '') {
            return false;
        }
        $key = self::_sha1prng($key);
        $decoded = base64_decode($cipher);
        if ($decoded){
            if(version_compare(PHP_VERSION,'7.1','>=')){
                $iv = '';
                return  openssl_decrypt($decoded, 'AES-128-ECB', $key, OPENSSL_RAW_DATA, $iv);
            }else{
                $block_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
                $iv         = mcrypt_create_iv($block_size, MCRYPT_RAND);
                $decrypted  = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $decoded, MCRYPT_MODE_ECB, $iv);
                return self::_pkcs5_unpad($decrypted);
            }
        }
        return false;
    }

    /**
     * SHA1PRNG算法
     * @param $key
     * @return string
     */
    private static function _sha1prng($key)
    {
        return substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
    }

    private static function _pkcs5_pad($text, $block_size)
    {
        $pad = $block_size - (strlen($text) % $block_size);
        return $text . str_repeat(chr($pad), $pad);
    }

    private static function _pkcs5_unpad($text)
    {
        $end  = substr($text, -1);
        $last = ord($end);
        $len  = strlen($text) - $last;
        if (substr($text, $len) == str_repeat($end, $last)) {
            return substr($text, 0, $len);
        }
        return false;
    }
}

//使用方法:
$keyStr = 'sdez';
$aes = new Aes();
$str = '{"openCode":"a9ae-8394-49bb","phone":"9988","name":"test","type":"2"}';
$chgstr = $aes->encrypt($str,$keyStr);
echo $chgstr;
echo PHP_EOL;
$rstr = $aes->decrypt($chgstr,$keyStr);
echo $rstr;

你可能感兴趣的:(php)