Better randomid generation (?)
authorMichael M Slusarz <slusarz@curecanti.org>
Wed, 11 Aug 2010 00:05:34 +0000 (18:05 -0600)
committerMichael M Slusarz <slusarz@curecanti.org>
Wed, 11 Aug 2010 00:08:27 +0000 (18:08 -0600)
Since uniqid() is essentially microtime(), adding microtime()
information does not get us anything. So use uniqid/mt_rand exclusively,
add a bit more entropy with the current PID, and encode with base64 -
packs even more info into the characters.

framework/Support/lib/Horde/Support/Randomid.php
framework/Support/test/Horde/Support/RandomidTest.php

index 703c70f..150effc 100644 (file)
@@ -8,12 +8,12 @@
 
 /**
  * Class for generating a random ID string. This string uses all characters
- * in the class [0-9a-z].
+ * in the class [0-9a-zA-Z].
  *
  * <code>
  *  <?php
  *
- *  $rid = (string)new Horde_Support_Randomid([$length = 16]);
+ *  $rid = (string)new Horde_Support_Randomid();
  *
  *  ?>
  * </code>
@@ -35,22 +35,18 @@ class Horde_Support_Randomid
 
     /**
      * New random ID.
-     *
-     * @param integer $length  The length of the ID.
      */
-    public function __construct($length = 16)
+    public function __construct()
     {
-        $this->generate($length);
+        $this->generate();
     }
 
     /**
      * Generate a random ID.
-     *
-     * @param integer $length  The length of the ID.
      */
-    public function generate($length = 16)
+    public function generate()
     {
-        $this->_rid = substr(base_convert(dechex(strtr(microtime(), array('0.' => '', ' ' => ''))) . strtr(uniqid(mt_rand(), true), array('.' => '')), 16, 36), 0, $length);
+        $this->_rid = rtrim(base64_encode(pack('H*', strtr(uniqid(mt_rand(), true), array('.' => '')) . dechex(getmypid()))), '=');
     }
 
     /**
index e710b83..7645ba1 100644 (file)
  */
 class Horde_Support_RandomidTest extends PHPUnit_Framework_TestCase
 {
-    public function testRandomidLength()
-    {
-        $rid = (string)new Horde_Support_Randomid;
-        $this->assertEquals(16, strlen($rid));
-    }
-
     public function testRandomidDuplicates()
     {
         $values = array();