首页 > 技术文章 > PHP 使用AES加密,并扩展失效时间检测

xfstu 2021-12-19 14:01 原文

/**
 * 具有时间校验的AES加密
 * @param string $string 要处理的字符串
 * @param int $timeout 超时时间,单位秒
 * @param string $type 处理类型,默认是加密
 * @return string 返回字符串
 */
public function AES($str, $timeout = null, $type = 'dec')
{
    $key = 'xfstu';
    $time = time();
    if ($type == 'enc') {
        if ($timeout) {
            $str = '1' . ($timeout + $time) . $str;
        } else {
            $str = '0' . $time . $str;
        }
        return str_replace('=', '', base64_encode(openssl_encrypt($str, 'AES-128-ECB', $key)));
    }
    $str = openssl_decrypt(base64_decode($str), 'AES-128-ECB', $key);
    $type = substr($str, 0, 1);
    if ($type == '1') {
        if (substr($str, 1, 10) - time() <= 0) {
            return null;
        }
        return substr($str, 11);
    }
    return substr($str, 11);
}

 

推荐阅读