minor #18085 [Cache] Hash using B64+MD5 in FilesystemAdapter (nicolas-grekas)
This PR was merged into the 3.1-dev branch.
Discussion
----------
[Cache] Hash using B64+MD5 in FilesystemAdapter
| Q | A
| ------------- | ---
| Branch | master
| Bug fix? | no
| New feature? | no
| BC breaks? | no
| Deprecations? | no
| Tests pass? | no
| Fixed tickets | -
| License | MIT
| Doc PR | -
Using MD5+B64 is good enough to avoid any hash collision, even on case-insensitive filesystems.
On Windows where the total path length is limited, this saves 44 chars worth.
Even if collisions are extremely unlikely, they are detected by adding then comparing the raw key to saved payloads. This also has the added benefit of easing debugging/grepping the cached items on the filesystem.
Commits
-------
e96bb10
[Cache] Hash using B64+MD5 in FilesystemAdapter
This commit is contained in:
commit
117d83bd95
@ -40,7 +40,7 @@ class FilesystemAdapter extends AbstractAdapter
|
||||
throw new InvalidArgumentException(sprintf('Cache directory is not writable (%s)', $directory));
|
||||
}
|
||||
// On Windows the whole path is limited to 258 chars
|
||||
if ('\\' === DIRECTORY_SEPARATOR && strlen($dir) > 190) {
|
||||
if ('\\' === DIRECTORY_SEPARATOR && strlen($dir) > 234) {
|
||||
throw new InvalidArgumentException(sprintf('Cache directory too long (%s)', $directory));
|
||||
}
|
||||
|
||||
@ -68,12 +68,15 @@ class FilesystemAdapter extends AbstractAdapter
|
||||
@unlink($file);
|
||||
}
|
||||
} else {
|
||||
$i = rawurldecode(rtrim(fgets($h)));
|
||||
$value = stream_get_contents($h);
|
||||
flock($h, LOCK_UN);
|
||||
fclose($h);
|
||||
if ($i === $id) {
|
||||
$values[$id] = unserialize($value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
@ -131,7 +134,7 @@ class FilesystemAdapter extends AbstractAdapter
|
||||
if (!file_exists($dir)) {
|
||||
@mkdir($dir, 0777, true);
|
||||
}
|
||||
$value = $expiresAt."\n".serialize($value);
|
||||
$value = $expiresAt."\n".rawurlencode($id)."\n".serialize($value);
|
||||
if (false !== @file_put_contents($file, $value, LOCK_EX)) {
|
||||
@touch($file, $expiresAt);
|
||||
} else {
|
||||
@ -144,8 +147,8 @@ class FilesystemAdapter extends AbstractAdapter
|
||||
|
||||
private function getFile($id)
|
||||
{
|
||||
$hash = hash('sha256', $id);
|
||||
$hash = str_replace('/', '-', base64_encode(md5($id, true)));
|
||||
|
||||
return $this->directory.$hash[0].DIRECTORY_SEPARATOR.$hash[1].DIRECTORY_SEPARATOR.$hash;
|
||||
return $this->directory.$hash[0].DIRECTORY_SEPARATOR.$hash[1].DIRECTORY_SEPARATOR.substr($hash, 2, -2);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user