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