[PHP] AES-ECB-128 + pkcs5加密

大憨熊 提交于 2019-11-29 23:41:22

AES-ECB-128 pkcs5填充加解密

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($str, 'AES-128-ECB', $encryptKey, OPENSSL_RAW_DATA);
        }

        return $decrypted;
    }
}

AES在线测试

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!