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