Browse Source

Add method to generate secure random strings.

ADmad 8 years ago
parent
commit
41a63c767e
2 changed files with 28 additions and 0 deletions
  1. 12 0
      src/Utility/Security.php
  2. 16 0
      tests/TestCase/Utility/SecurityTest.php

+ 12 - 0
src/Utility/Security.php

@@ -134,6 +134,18 @@ class Security
     }
 
     /**
+     * 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.
      *
      * @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(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
      *
      * @return void