diff --git a/src/Utility/Security.php b/src/Utility/Security.php index 152da0e4430..bf59e68dd4c 100644 --- a/src/Utility/Security.php +++ b/src/Utility/Security.php @@ -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. * diff --git a/tests/TestCase/Utility/SecurityTest.php b/tests/TestCase/Utility/SecurityTest.php index 911ca6938e3..39d0862ce89 100644 --- a/tests/TestCase/Utility/SecurityTest.php +++ b/tests/TestCase/Utility/SecurityTest.php @@ -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 *