Merge pull request #273 from sarciszewski/patch-1

Make Util/KeyAlgorithm/DefaultAlgorithm guarantee $len bytes of output even in edge cases.
This commit is contained in:
Alex Bilbie 2014-12-09 12:53:04 +00:00
commit 0ce7ecb45a

View File

@ -18,10 +18,9 @@ class DefaultAlgorithm implements KeyAlgorithmInterface
*/ */
public function generate($len = 40) public function generate($len = 40)
{ {
// We generate twice as many bytes here because we want to ensure we have $stripped = '';
// enough after we base64 encode it to get the length we need because we do {
// take out the "/", "+", and "=" characters. $bytes = openssl_random_pseudo_bytes($len, $strong);
$bytes = openssl_random_pseudo_bytes($len * 2, $strong);
// We want to stop execution if the key fails because, well, that is bad. // We want to stop execution if the key fails because, well, that is bad.
if ($bytes === false || $strong === false) { if ($bytes === false || $strong === false) {
@ -29,7 +28,8 @@ class DefaultAlgorithm implements KeyAlgorithmInterface
throw new \Exception('Error Generating Key'); throw new \Exception('Error Generating Key');
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
} }
$stripped .= str_replace(['/', '+', '='], '', base64_encode($bytes));
return substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $len); } while (strlen($stripped) < $len);
return substr($stripped, 0, $len);
} }
} }