]> git.mxchange.org Git - core.git/blobdiff - framework/main/classes/rng/class_RandomNumberGenerator.php
Continued with renaming-season:
[core.git] / framework / main / classes / rng / class_RandomNumberGenerator.php
diff --git a/framework/main/classes/rng/class_RandomNumberGenerator.php b/framework/main/classes/rng/class_RandomNumberGenerator.php
new file mode 100644 (file)
index 0000000..515d788
--- /dev/null
@@ -0,0 +1,224 @@
+<?php
+// Own namespace
+namespace CoreFramework\Crypto\RandomNumber;
+
+// Import framework stuff
+use CoreFramework\Object\BaseFrameworkSystem;
+use CoreFramework\Generic\FrameworkInterface;
+
+/**
+ * A standard random number generator
+ *
+ * @author             Roland Haeder <webmaster@shipsimu.org>
+ * @version            0.0.0
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @license            GNU GPL 3.0 or any newer version
+ * @link               http://www.shipsimu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class RandomNumberGenerator extends BaseFrameworkSystem {
+       /**
+        * Prime number for better pseudo random numbers
+        */
+       private $prime = 0;
+
+       /**
+        * Add this calculated number to the rng
+        */
+       private $extraNumber = 0;
+
+       /**
+        * Extra salt for secured hashing
+        */
+       private $extraSalt = '';
+
+       /**
+        * Fixed salt for secured hashing
+        */
+       private $fixedSalt = '';
+
+       /**
+        * Maximum length for random string
+        */
+       private $rndStrLen = 0;
+
+       /**
+        * Self instance
+        */
+       private static $selfInstance = NULL;
+
+       /**
+        * Protected constructor
+        *
+        * @param       $className      Name of this class
+        * @return      void
+        */
+       protected function __construct ($className = __CLASS__) {
+               // Call parent constructor
+               parent::__construct($className);
+       }
+
+       /**
+        * Creates an instance of this class
+        *
+        * @param       $extraInstance  An extra instance for more salt (default: null)
+        * @return      $rngInstance    An instance of this random number generator
+        */
+       public static final function createRandomNumberGenerator (FrameworkInterface $extraInstance = NULL) {
+               // Is self instance set?
+               if (is_null(self::$selfInstance)) {
+                       // Get a new instance
+                       $rngInstance = new RandomNumberGenerator();
+
+                       // Initialize the RNG now
+                       $rngInstance->initRng($extraInstance);
+
+                       // Set it "self"
+                       self::$selfInstance = $rngInstance;
+               } else {
+                       // Use from self instance
+                       $rngInstance = self::$selfInstance;
+               }
+
+               // Return the instance
+               return $rngInstance;
+       }
+
+       /**
+        * Initializes the random number generator
+        *
+        * @param       $extraInstance  An extra instance for more salt (default: null)
+        * @return      void
+        * @todo        Add site key for stronger salt!
+        */
+       protected function initRng ($extraInstance) {
+               // Get the prime number from config
+               $this->prime = $this->getConfigInstance()->getConfigEntry('math_prime');
+
+               // Calculate the extra number which is always the same unless you give
+               // a better prime number
+               $this->extraNumber = ($this->prime * $this->prime / pow(pi(), 2));
+
+               // Seed mt_rand()
+               mt_srand((double) sqrt(microtime(TRUE) * 100000000 * $this->extraNumber));
+
+               // Set the server IP to cluster
+               $serverIp = 'cluster';
+
+               // Do we have a single server?
+               if ($this->getConfigInstance()->getConfigEntry('is_single_server') == 'Y') {
+                       // Then use that IP for extra security
+                       $serverIp = $this->getConfigInstance()->detectServerAddress();
+               } // END - if
+
+               // Yet-another fixed salt. This is not dependend on server software or date
+               if ($extraInstance instanceof FrameworkInterface) {
+                       // With extra instance information
+                       $this->fixedSalt = sha1(
+                               $serverIp . ':' .
+                               $extraInstance->__toString() . ':' .
+                               json_encode($this->getDatabaseInstance()->getConnectionData())
+                       );
+               } else {
+                       // Without extra information
+                       $this->fixedSalt = sha1($serverIp . ':' . json_encode($this->getDatabaseInstance()->getConnectionData()));
+               }
+
+               // One-way data we need for "extra-salting" the random number
+               $this->extraSalt = sha1(
+                       $this->fixedSalt . ':' .
+                       getenv('SERVER_SOFTWARE') . ':' .
+                       $this->getConfigInstance()->getConfigEntry('date_key') . ':' .
+                       $this->getConfigInstance()->getConfigEntry('base_url')
+               );
+
+               // Get config entry for max salt length
+               $this->rndStrLen = $this->getConfigInstance()->getConfigEntry('rnd_str_length');
+       }
+
+       /**
+        * Makes a pseudo-random string useable for salts
+        *
+        * @param       $length                 Length of the string, default: 128
+        * @return      $randomString   The pseudo-random string
+        */
+       public function randomString ($length = -1) {
+               // Is the number <1, then fix it to default length
+               if ($length < 1) {
+                       $length = $this->rndStrLen;
+               } // END - if
+
+               // Initialize the string
+               $randomString = '';
+
+               // And generate it
+               for ($idx = 0; $idx < $length; $idx++) {
+                       // Add a random character and add it to our string
+                       $randomString .= chr($this->randomNumber(0, 255));
+               } // END - for
+
+               // Return the random string a little mixed up
+               return str_shuffle($randomString);
+       }
+
+       /**
+        * Generate a pseudo-random integer number in a given range
+        *
+        * @param       $min    Min value to generate
+        * @param       $max    Max value to generate
+        * @return      $num    Pseudo-random number
+        * @todo        I had a better random number generator here but now it is somewhere lost :(
+        */
+       public function randomNumber ($min, $max) {
+               return mt_rand($min, $max);
+       }
+
+       /**
+        * Getter for extra salt
+        *
+        * @return      $extraSalt
+        */
+       public final function getExtraSalt () {
+               return $this->extraSalt;
+       }
+
+       /**
+        * Getter for fixed salt
+        *
+        * @return      $fixedSalt
+        */
+       public final function getFixedSalt () {
+               return $this->fixedSalt;
+       }
+
+       /**
+        * Generates a key based on if we have extra (default) or fixed salt enabled
+        *
+        * @return      $key    The generated key for encryption
+        */
+       public function generateKey () {
+               // Default is extra salt
+               $key = md5($this->getExtraSalt());
+
+               // Get key
+               if ($this->getConfigInstance()->getConfigEntry('crypt_fixed_salt') == 'Y') {
+                       $key = md5($this->getFixedSalt());
+               } // END - if
+
+               // Return it
+               return $key;
+       }
+
+}