What’s new in PHP 7.2

注意:需要完整版本的 PHP 7.2 新特性介绍请查看官方文档或者翻译版本。本文只会介绍我自己感兴趣的部分。


Moving MCrypt to PECL

MCrypt 扩展从 PHP 7.1 版本开始被标记为废弃,在 PHP 7.2 版本正式从 PHP 核心移到 PECL。相应的,Sodium 扩展从 PECL 移到了 PHP 核心。(由于 libmcrypt 从 2007 年开始就再也没有更新过,所以强烈建议不要再使用 MCrypt 扩展,推荐使用 OpenSSL 或者 Sodium 扩展。)

下面是分别用 MCrypt,OpenSSL,Sodium 三种扩展实现的加密和解密方法,具体可以查看:https://github.com/tanghengzhi/php-crypto。

PHP Extension Algorithm
Mcrypt AES256-ECB
OpenSSL AES256-CBC
Sodium AES256-GCM

trait Key {
    public static $key = "secret\0\0\0\0\0\0\0\0\0\0";
}

class Mcrypt {
    use Key;
    public static function encrypt($data) {
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
        $encryptText = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::$key, $data, MCRYPT_MODE_ECB, $iv);
        return base64_encode($encryptText);
    }

    public static function decrypt($data) {
        $encryptText = base64_decode($data);
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
        $decryptText = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::$key, $encryptText, MCRYPT_MODE_ECB, $iv);
        return $decryptText;
    }
}

class OpenSSL {
    use Key;

    public static function encrypt($data) {
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC'));
        $encryptText = openssl_encrypt($data, 'AES-256-CBC', self::$key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . "::" . $encryptText);
    }

    public static function decrypt($data) {
        list($iv, $encryptText) = explode('::', base64_decode($data));
        $decryptText = openssl_decrypt($encryptText, 'AES-256-CBC', self::$key, OPENSSL_RAW_DATA, $iv);
        return $decryptText;
    }
}

class Sodium {
    use Key;

    public static function encrypt($data) {
        $nonce = random_bytes(SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES);
        $encryptText = sodium_crypto_aead_aes256gcm_encrypt($data, '', $nonce, str_pad(self::$key, SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES));
        return base64_encode($nonce . "::" . $encryptText);
    }

    public static function decrypt($data) {
        list($nonce, $encryptText) = explode('::', base64_decode($data));
        $decryptText = sodium_crypto_aead_aes256gcm_decrypt($encryptText, '', $nonce, str_pad(self::$key, SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES));
        return $decryptText;
    }
}

imageantialias() is now also available if compiled with a system libgd.

曾经因为 Ubuntu 系统自带的 php70-gd 不支持 imageantialias() 折腾了一天,现在这个问题终于解决了。

Exciting!!!


参考:

http://php.net/manual/en/migration72.php

https://laravel-china.org/topics/9814/introduction-of-new-functions-of-php-72

 930 total views,  3 views today

Leave a Reply

Your email address will not be published. Required fields are marked *