From 7a63f42462ca098a5933f3e24b50cbf7964f1e41 Mon Sep 17 00:00:00 2001 From: Scott Arciszewski Date: Mon, 8 Dec 2014 18:40:31 -0500 Subject: [PATCH] Update DefaultAlgorithm.php Prevent edge-case whereby, if the majority of `base64_encode($bytes)` consists of `/` or `+` characters, the resulting key will be shorter and less unpredictable (due to a smaller keyspace) than anticipated. As a result, the `$len * 2` hack has been removed. Although it is highly probable that `$len * 2` will stop most edge cases from occurring, it does not actually guarantee the end result will be at least 40 characters long. --- src/Util/KeyAlgorithm/DefaultAlgorithm.php | 26 +++++++++++----------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Util/KeyAlgorithm/DefaultAlgorithm.php b/src/Util/KeyAlgorithm/DefaultAlgorithm.php index 08c4009a..14cc5273 100644 --- a/src/Util/KeyAlgorithm/DefaultAlgorithm.php +++ b/src/Util/KeyAlgorithm/DefaultAlgorithm.php @@ -18,18 +18,18 @@ class DefaultAlgorithm implements KeyAlgorithmInterface */ public function generate($len = 40) { - // We generate twice as many bytes here because we want to ensure we have - // enough after we base64 encode it to get the length we need because we - // take out the "/", "+", and "=" characters. - $bytes = openssl_random_pseudo_bytes($len * 2, $strong); - - // We want to stop execution if the key fails because, well, that is bad. - if ($bytes === false || $strong === false) { - // @codeCoverageIgnoreStart - throw new \Exception('Error Generating Key'); - // @codeCoverageIgnoreEnd - } - - return substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $len); + $stripped = ''; + do { + $bytes = openssl_random_pseudo_bytes($len, $strong); + + // We want to stop execution if the key fails because, well, that is bad. + if ($bytes === false || $strong === false) { + // @codeCoverageIgnoreStart + throw new \Exception('Error Generating Key'); + // @codeCoverageIgnoreEnd + } + $stripped .= str_replace(['/', '+', '='], '', base64_encode($bytes)); + } while (strlen($stripped) < $len); + return substr($stripped, 0, $len); } }