[PHP] AES-ECB-128 + pkcs5加解密代码

AES-ECB-128 pkcs5填充加解密

注意:秘钥建议设置长度使用16位,超过16位后会出现异常情况。未查明具体原因但是可能和PHP版本有关系。可以用PHP 7.1+与PHP 5+版本尝试。
class AesEncryptService
{
    /**
     * @desc AES-128-ECB加密
     * @param $str
     * @param $encryptKey
     * @return string
     */
    public static function AesEncrypt($str, $encryptKey)
    {

        if (version_compare(PHP_VERSION, '7.1.0', '<')) {
            $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
            $input = self::addPKCS5Padding($str, $size);
            $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
            $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
            mcrypt_generic_init($td, $encryptKey, $iv);
            $data = mcrypt_generic($td, $input);
            mcrypt_generic_deinit($td);
            mcrypt_module_close($td);

        } else {

            $data = openssl_encrypt($str, 'AES-128-ECB', $encryptKey, OPENSSL_RAW_DATA);

        }
        $data = base64_encode($data);
        return $data;
    }

    /**
     * @desc    添加PKCS5填充
     * @param $source
     * @param $size
     * @return string
     */
    private static function addPKCS5Padding($source, $size)
    {
        $pad = $size - (strlen($source) % $size);
        return $source . str_repeat(chr($pad), $pad);
    }

    /**
     * @desc 去除PKCS5填充
     * @param $decrypted
     * @return string
     */
    private static function unsetPKCS5Padding($decrypted)
    {
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s - 1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }

    /**
     * @desc AES-128-ECB解密方法
     * @param string $str
     * @param string $encryptKey
     * @return string
     */
    public static function AesDecrypt( $str, $encryptKey)
    {

        if (version_compare(PHP_VERSION, '7.1.0', '<')) {
            $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $encryptKey, base64_decode($str), MCRYPT_MODE_ECB);
            $decrypted = self::unsetPKCS5Padding($decrypted);
        } else {
            $decrypted = openssl_decrypt(base64_decode($str), 'AES-128-ECB', $encryptKey, OPENSSL_RAW_DATA);
        }

        return $decrypted;
    }
}

AES在线测试

你可能感兴趣的:(代码片段,PHP,加密/解密)