Skip to content

Commit

Permalink
Add method to generate secure random strings.
Browse files Browse the repository at this point in the history
  • Loading branch information
ADmad committed Feb 1, 2018
1 parent eb36fdf commit 41a63c7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Utility/Security.php
Expand Up @@ -133,6 +133,18 @@ public static function randomBytes($length)
return $bytes;
}

/**
* Creates a secure random string.
*
* @param int $length String length
* @return string
* @since 3.6.0
*/
public static function randomString($length)
{
return bin2hex(Security::randomBytes($length / 2));
}

/**
* Like randomBytes() above, but not cryptographically secure.
*
Expand Down
16 changes: 16 additions & 0 deletions tests/TestCase/Utility/SecurityTest.php
Expand Up @@ -334,6 +334,22 @@ public function testRandomBytes()
$this->assertRegExp('/[^0-9a-f]/', $value, 'should return a binary string');
}

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

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

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

/**
* Test the insecureRandomBytes method
*
Expand Down

0 comments on commit 41a63c7

Please sign in to comment.