Skip to content

Commit

Permalink
Merge pull request #8869 from chinpei215/random-bytes-fallback
Browse files Browse the repository at this point in the history
Fix Security::randomBytes() fallback
  • Loading branch information
markstory committed May 21, 2016
2 parents babc83b + e4acb35 commit e3c8d8a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
18 changes: 17 additions & 1 deletion src/Utility/Security.php
Expand Up @@ -121,13 +121,29 @@ public static function randomBytes($length)
'Falling back to an insecure random source.',
E_USER_WARNING
);
return static::insecureRandomBytes($length);
}

/**
* Like randomBytes() above, but not cryptographically secure.
*
* @param int $length The number of bytes you want.
* @return string Random bytes in binary.
* @see \Cake\Utility\Security::randomBytes()
*/
public static function insecureRandomBytes($length)
{
$length *= 2;

$bytes = '';
$byteLength = 0;
while ($byteLength < $length) {
$bytes .= static::hash(Text::uuid() . uniqid(mt_rand(), true), 'sha512', true);
$byteLength = strlen($bytes);
}
return substr($bytes, 0, $length);
$bytes = substr($bytes, 0, $length);

return pack('H*', $bytes);
}

/**
Expand Down
20 changes: 19 additions & 1 deletion tests/TestCase/Utility/SecurityTest.php
Expand Up @@ -294,7 +294,7 @@ public function testSalt()
}

/**
* Test the random method.
* Test the randomBytes method.
*
* @return void
*/
Expand All @@ -305,5 +305,23 @@ public function testRandomBytes()

$value = Security::randomBytes(64);
$this->assertSame(64, strlen($value));

$this->assertRegExp('/[^0-9a-f]/', $value, 'should return a binary string');
}

/**
* Test the insecureRandomBytes method
*
* @return void
*/
public function testInsecureRandomBytes()
{
$value = Security::insecureRandomBytes(16);
$this->assertSame(16, strlen($value));

$value = Security::insecureRandomBytes(64);
$this->assertSame(64, strlen($value));

$this->assertRegExp('/[^0-9a-f]/', $value, 'should return a binary string');
}
}

0 comments on commit e3c8d8a

Please sign in to comment.