Some updates:
[core.git] / framework / main / classes / rng / class_RandomNumberGenerator.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Crypto\RandomNumber;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
8 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
9
10 /**
11  * A standard random number generator
12  *
13  * @author              Roland Haeder <webmaster@shipsimu.org>
14  * @version             0.0.0
15 <<<<<<< HEAD:framework/main/classes/rng/class_RandomNumberGenerator.php
16  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
17 =======
18  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
19 >>>>>>> Some updates::inc/main/classes/rng/class_RandomNumberGenerator.php
20  * @license             GNU GPL 3.0 or any newer version
21  * @link                http://www.shipsimu.org
22  *
23  * This program is free software: you can redistribute it and/or modify
24  * it under the terms of the GNU General Public License as published by
25  * the Free Software Foundation, either version 3 of the License, or
26  * (at your option) any later version.
27  *
28  * This program is distributed in the hope that it will be useful,
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31  * GNU General Public License for more details.
32  *
33  * You should have received a copy of the GNU General Public License
34  * along with this program. If not, see <http://www.gnu.org/licenses/>.
35  */
36 class RandomNumberGenerator extends BaseFrameworkSystem {
37         /**
38          * Prime number for better pseudo random numbers
39          */
40         private $prime = 0;
41
42         /**
43          * Add this calculated number to the rng
44          */
45         private $extraNumber = 0;
46
47         /**
48          * Extra salt for secured hashing
49          */
50         private $extraSalt = '';
51
52         /**
53          * Fixed salt for secured hashing
54          */
55         private $fixedSalt = '';
56
57         /**
58          * Maximum length for random string
59          */
60         private $rndStrLen = 0;
61
62         /**
63          * Self instance
64          */
65         private static $selfInstance = NULL;
66
67         /**
68          * Protected constructor
69          *
70          * @param       $className      Name of this class
71          * @return      void
72          */
73         protected function __construct ($className = __CLASS__) {
74                 // Call parent constructor
75                 parent::__construct($className);
76         }
77
78         /**
79          * Creates an instance of this class
80          *
81          * @param       $extraInstance  An extra instance for more salt (default: null)
82          * @return      $rngInstance    An instance of this random number generator
83          */
84         public static final function createRandomNumberGenerator (FrameworkInterface $extraInstance = NULL) {
85                 // Is self instance set?
86                 if (is_null(self::$selfInstance)) {
87                         // Get a new instance
88                         $rngInstance = new RandomNumberGenerator();
89
90                         // Initialize the RNG now
91                         $rngInstance->initRng($extraInstance);
92
93                         // Set it "self"
94                         self::$selfInstance = $rngInstance;
95                 } else {
96                         // Use from self instance
97                         $rngInstance = self::$selfInstance;
98                 }
99
100                 // Return the instance
101                 return $rngInstance;
102         }
103
104         /**
105          * Initializes the random number generator
106          *
107          * @param       $extraInstance  An extra instance for more salt (default: null)
108          * @return      void
109          * @todo        Add site key for stronger salt!
110          */
111         protected function initRng ($extraInstance) {
112                 // Get the prime number from config
113                 $this->prime = $this->getConfigInstance()->getConfigEntry('math_prime');
114
115                 // Calculate the extra number which is always the same unless you give
116                 // a better prime number
117                 $this->extraNumber = ($this->prime * $this->prime / pow(pi(), 2));
118
119                 // Seed mt_rand()
120                 mt_srand((double) sqrt(microtime(true) * 100000000 * $this->extraNumber));
121
122                 // Set the server IP to cluster
123                 $serverIp = 'cluster';
124
125                 // Do we have a single server?
126                 if ($this->getConfigInstance()->getConfigEntry('is_single_server') == 'Y') {
127                         // Then use that IP for extra security
128                         $serverIp = FrameworkBootstrap::detectServerAddress();
129                 } // END - if
130
131                 // Yet-another fixed salt. This is not dependend on server software or date
132                 if ($extraInstance instanceof FrameworkInterface) {
133                         // With extra instance information
134                         $this->fixedSalt = sha1(
135                                 $serverIp . ':' .
136                                 $extraInstance->__toString() . ':' .
137                                 json_encode($this->getDatabaseInstance()->getConnectionData())
138                         );
139                 } else {
140                         // Without extra information
141                         $this->fixedSalt = sha1($serverIp . ':' . json_encode($this->getDatabaseInstance()->getConnectionData()));
142                 }
143
144                 // One-way data we need for "extra-salting" the random number
145                 $this->extraSalt = sha1(
146                         $this->fixedSalt . ':' .
147                         getenv('SERVER_SOFTWARE') . ':' .
148                         $this->getConfigInstance()->getConfigEntry('date_key') . ':' .
149                         $this->getConfigInstance()->getConfigEntry('base_url')
150                 );
151
152                 // Get config entry for max salt length
153                 $this->rndStrLen = $this->getConfigInstance()->getConfigEntry('rnd_str_length');
154         }
155
156         /**
157          * Makes a pseudo-random string useable for salts
158          *
159          * @param       $length                 Length of the string, default: 128
160          * @return      $randomString   The pseudo-random string
161          */
162         public function randomString ($length = -1) {
163                 // Is the number <1, then fix it to default length
164                 if ($length < 1) {
165                         $length = $this->rndStrLen;
166                 } // END - if
167
168                 // Initialize the string
169                 $randomString = '';
170
171                 // And generate it
172                 for ($idx = 0; $idx < $length; $idx++) {
173                         // Add a random character and add it to our string
174                         $randomString .= chr($this->randomNumber(0, 255));
175                 } // END - for
176
177                 // Return the random string a little mixed up
178                 return str_shuffle($randomString);
179         }
180
181         /**
182          * Generate a pseudo-random integer number in a given range
183          *
184          * @param       $min    Min value to generate
185          * @param       $max    Max value to generate
186          * @return      $num    Pseudo-random number
187          * @todo        I had a better random number generator here but now it is somewhere lost :(
188          */
189         public function randomNumber ($min, $max) {
190                 return mt_rand($min, $max);
191         }
192
193         /**
194          * Getter for extra salt
195          *
196          * @return      $extraSalt
197          */
198         public final function getExtraSalt () {
199                 return $this->extraSalt;
200         }
201
202         /**
203          * Getter for fixed salt
204          *
205          * @return      $fixedSalt
206          */
207         public final function getFixedSalt () {
208                 return $this->fixedSalt;
209         }
210
211         /**
212          * Generates a key based on if we have extra (default) or fixed salt enabled
213          *
214          * @return      $key    The generated key for encryption
215          */
216         public function generateKey () {
217                 // Default is extra salt
218                 $key = md5($this->getExtraSalt());
219
220                 // Get key
221                 if ($this->getConfigInstance()->getConfigEntry('crypt_fixed_salt') == 'Y') {
222                         $key = md5($this->getFixedSalt());
223                 } // END - if
224
225                 // Return it
226                 return $key;
227         }
228
229 }