Browse Source

Merge pull request #11679 from cakephp/random-string

Add method to generate secure random strings.
Mark Story 8 years ago
parent
commit
92b140bac0
2 changed files with 32 additions and 0 deletions
  1. 16 0
      src/Utility/Security.php
  2. 16 0
      tests/TestCase/Utility/SecurityTest.php

+ 16 - 0
src/Utility/Security.php

@@ -134,6 +134,22 @@ class Security
     }
 
     /**
+     * Creates a secure random string.
+     *
+     * @param int $length String length. Default 64.
+     * @return string
+     * @since 3.6.0
+     */
+    public static function randomString($length = 64)
+    {
+        return substr(
+            bin2hex(Security::randomBytes(ceil($length / 2))),
+            0,
+            $length
+        );
+    }
+
+    /**
      * Like randomBytes() above, but not cryptographically secure.
      *
      * @param int $length The number of bytes you want.

+ 16 - 0
tests/TestCase/Utility/SecurityTest.php

@@ -335,6 +335,22 @@ class SecurityTest extends TestCase
     }
 
     /**
+     * Test the randomString method.
+     *
+     * @return void
+     */
+    public function testRandomString()
+    {
+        $value = Security::randomString(7);
+        $this->assertSame(7, strlen($value));
+
+        $value = Security::randomString();
+        $this->assertSame(64, strlen($value));
+
+        $this->assertRegExp('/^[0-9a-f]+$/', $value, 'should return a ASCII string');
+    }
+
+    /**
      * Test the insecureRandomBytes method
      *
      * @return void