Continued:
[core.git] / framework / main / classes / crypto / class_CryptoHelper.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Helper\Crypto;
4
5 // Import framework stuff
6 use CoreFramework\Crypto\Cryptable;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Object\BaseFrameworkSystem;
9
10 /**
11  * A helper class for cryptographical things like hashing passwords and so on
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 CryptoHelper extends BaseFrameworkSystem implements Cryptable {
33         // Exception constants
34         const EXCEPTION_ENCRYPT_MISSING = 0x1f0;
35         const EXCEPTION_ENCRYPT_INVALID = 0x1f1;
36
37         /**
38          * An instance of this own clas
39          */
40         private static $selfInstance = NULL;
41
42         /**
43          * Instance of the crypto stream
44          */
45         private $cryptoStreamInstance = NULL;
46
47         /**
48          * Salt for hashing operations
49          */
50         private $salt = '';
51
52         /**
53          * Protected constructor
54          *
55          * @return      void
56          */
57         protected function __construct () {
58                 // Call parent constructor
59                 parent::__construct(__CLASS__);
60         }
61
62         /**
63          * Creates an instance of this class
64          *
65          * @return      $cryptoInstance         An instance of this crypto helper class
66          */
67         public static final function createCryptoHelper () {
68                 // Get a new instance
69                 $cryptoInstance = new CryptoHelper();
70
71                 // Initialize the hasher
72                 $cryptoInstance->initHasher();
73
74                 // Attach a crypto stream
75                 $cryptoInstance->attachCryptoStream();
76
77                 // Return the instance
78                 return $cryptoInstance;
79         }
80
81         /**
82          * Get a singleton instance of this class
83          *
84          * @return      $selfInstance   An instance of this crypto helper class
85          */
86         public static final function getSelfInstance () {
87                 // Is no instance there?
88                 if (is_null(self::$selfInstance)) {
89                         // Then get a new one
90                         self::$selfInstance = self::createCryptoHelper();
91                 } // END - if
92
93                 // Return the instance
94                 return self::$selfInstance;
95         }
96
97         /**
98          * Attaches a crypto stream to this crypto helper by detecting loaded
99          * modules.
100          *
101          * @return      void
102          */
103         protected function attachCryptoStream () {
104                 // Do we have mcrypt loaded?
105                 if ($this->isPhpExtensionLoaded('mcrypt')) {
106                         // Then use it
107                         $this->cryptoStreamInstance = ObjectFactory::createObjectByName('McryptStream', array($this->getRngInstance()));
108                 } else {
109                         // If nothing works ...
110                         $this->cryptoStreamInstance = ObjectFactory::createObjectByName('NullCryptoStream');
111                 }
112         }
113
114         /**
115          * Initializes the hasher for different purposes.
116          *
117          * @return      void
118          */
119         protected function initHasher () {
120                 // Initialize the random number generator which is required by some crypto methods
121                 $this->setRngInstance(ObjectFactory::createObjectByConfiguredName('rng_class'));
122
123                 // Generate a salt for the hasher
124                 $this->generateSalt();
125         }
126
127         /**
128          * Generates the salt based on configured length
129          *
130          * @return      void
131          */
132         private function generateSalt () {
133                 // Get a random string from the RNG
134                 $randomString = $this->getRngInstance()->randomString() . $this->createUuid();
135
136                 // Get config entry for salt length
137                 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
138
139                 // Keep only defined number of characters
140                 $this->salt = substr(sha1($randomString), -$length, $length);
141         }
142
143         /**
144          * Returns a UUID (Universal Unique IDentifier) if PECL extension uuid was
145          * found or an empty string it not.
146          *
147          * @return      $uuid   UUID with leading dash or empty string
148          */
149         public function createUuid () {
150                 // Init empty UUID
151                 $uuid = '';
152
153                 // Is the UUID extension loaded and enabled? (see pecl)
154                 if ($this->getConfigInstance()->getConfigEntry('extension_uuid_loaded') === TRUE) {
155                         // Then add it as well
156                         $uuid = uuid_create();
157                 } // END - if
158
159                 // Return it
160                 return $uuid;
161         }
162
163         /**
164          * Hashes a string with salt and returns the hash. If an old previous hash
165          * is supplied the method will use the first X chars of that hash for hashing
166          * the password. This is useful if you want to check if password is identical
167          * for authorization purposes.
168          *
169          * @param       $str            Unhashed string
170          * @param       $oldHash        A hash from previous hashed string
171          * @param       $withFixed      Whether to include a fixed salt (not recommended in p2p applications)
172          * @return      $hashed         The hashed and salted string
173          */
174         public function hashString ($str, $oldHash = '', $withFixed = TRUE) {
175                 // Cast the string
176                 $str = (string) $str;
177
178                 // Default is the default salt ;-)
179                 $salt = $this->salt;
180
181                 // Is the old password set?
182                 if (!empty($oldHash)) {
183                         // Use the salt from hash, first get length
184                         $length = $this->getConfigInstance()->getConfigEntry('salt_length');
185
186                         // Then extract the X first characters from the hash as our salt
187                         $salt = substr($oldHash, 0, $length);
188                 } // END - if
189
190                 // Hash the password with salt
191                 //* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
192                 if ($withFixed === TRUE) {
193                         // Use additional fixed salt
194                         $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_extra_mask'),
195                                 $salt,
196                                 $this->getRngInstance()->getFixedSalt(),
197                                 $str
198                         ));
199                 } else {
200                         // Use salt+string to hash
201                         $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_normal_mask'),
202                                 $salt,
203                                 $str
204                         ));
205                 }
206
207                 // And return it
208                 return $hashed;
209         }
210
211         /**
212          * Encrypt the string with fixed salt
213          *
214          * @param       $str            The unencrypted string
215          * @param       $key            Optional key, if none provided, a random key will be generated
216          * @return      $encrypted      Encrypted string
217          */
218         public function encryptString ($str, $key = NULL) {
219                 // Encrypt the string through the stream
220                 $encrypted = $this->cryptoStreamInstance->encryptStream($str, $key);
221
222                 // Return the string
223                 return $encrypted;
224         }
225
226         /**
227          * Decrypt the string with fixed salt
228          *
229          * @param       $encrypted      Encrypted string
230          * @return      $str            The unencrypted string
231          */
232         public function decryptString ($encrypted) {
233                 // Encrypt the string through the stream
234                 $str = $this->cryptoStreamInstance->decryptStream($encrypted);
235
236                 // Return the string
237                 return $str;
238         }
239
240 }