加密
public function encryptString($str,$key, int $ttl = 0)
{
$method = 'AES-128-CBC';
$ivLen = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivLen);
$str .= sprintf('%010d', $ttl > 0 ? $ttl + time() : 0);
$out = openssl_encrypt($str, $method, $key, OPENSSL_RAW_DATA, $iv);
if ($out === false) {
throw new \RuntimeException(openssl_error_string(), -1);
}
return str_replace('=', '', base64_encode($iv . $out));
}
解密
function decryptString($str, $key)
{
$str = base64_decode($str);
$method = 'AES-128-CBC';
$ivLen = openssl_cipher_iv_length('AES-128-CBC');
$iv = substr($str, 0, $ivLen);
$str = substr($str, $ivLen);
$data = openssl_decrypt($str, $method, $key, 1, $iv);
if ($data === false) {
throw new \RuntimeException(openssl_error_string(), -1);
}
$expireAt = intval(substr($data, -10));
if ($expireAt > 0 && time() > $expireAt) {
return false;
}
return substr($data, 0, -10);
}