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