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