]> git.mxchange.org Git - core.git/blob - inc/classes/main/crypto/class_CryptoHelper.php
Copyright year updated, converted double->single quotes
[core.git] / inc / classes / main / crypto / class_CryptoHelper.php
1 <?php
2 /**
3  * A helper class for cryptographical things like hashing passwords and so on
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.shipsimu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24 class CryptoHelper extends BaseFrameworkSystem implements Cryptable {
25         // Exception constants
26         const EXCEPTION_ENCRYPT_MISSING = 0x1f0;
27         const EXCEPTION_ENCRYPT_INVALID = 0x1f1;
28
29         /**
30          * An instance of this own clas
31          */
32         private static $selfInstance = NULL;
33
34         /**
35          * Instance of the crypto stream
36          */
37         private $cryptoStreamInstance = NULL;
38
39         /**
40          * Salt for hashing operations
41          */
42         private $salt = '';
43
44         /**
45          * Protected constructor
46          *
47          * @return      void
48          */
49         protected function __construct () {
50                 // Call parent constructor
51                 parent::__construct(__CLASS__);
52         }
53
54         /**
55          * Creates an instance of this class
56          *
57          * @return      $cryptoInstance         An instance of this crypto helper class
58          */
59         public static final function createCryptoHelper () {
60                 // Get a new instance
61                 $cryptoInstance = new CryptoHelper();
62
63                 // Initialize the hasher
64                 $cryptoInstance->initHasher();
65
66                 // Attach a crypto stream
67                 $cryptoInstance->attachCryptoStream();
68
69                 // Return the instance
70                 return $cryptoInstance;
71         }
72
73         /**
74          * Get a singleton instance of this class
75          *
76          * @return      $selfInstance   An instance of this crypto helper class
77          */
78         public static final function getSelfInstance () {
79                 // Is no instance there?
80                 if (is_null(self::$selfInstance)) {
81                         // Then get a new one
82                         self::$selfInstance = self::createCryptoHelper();
83                 } // END - if
84
85                 // Return the instance
86                 return self::$selfInstance;
87         }
88
89         /**
90          * Attaches a crypto stream to this crypto helper by detecting loaded
91          * modules.
92          *
93          * @return      void
94          */
95         protected function attachCryptoStream () {
96                 // Do we have mcrypt loaded?
97                 if ($this->isPhpExtensionLoaded('mcrypt')) {
98                         // Then use it
99                         $this->cryptoStreamInstance = ObjectFactory::createObjectByName('McryptStream', array($this->getRngInstance()));
100                 } else {
101                         // If nothing works ...
102                         $this->cryptoStreamInstance = ObjectFactory::createObjectByName('NullCryptoStream');
103                 }
104         }
105
106         /**
107          * Initializes the hasher for different purposes.
108          *
109          * @return      void
110          */
111         protected function initHasher () {
112                 // Initialize the random number generator which is required by some crypto methods
113                 $this->setRngInstance(ObjectFactory::createObjectByConfiguredName('rng_class'));
114
115                 // Generate a salt for the hasher
116                 $this->generateSalt();
117         }
118
119         /**
120          * Generates the salt based on configured length
121          *
122          * @return      void
123          */
124         private function generateSalt () {
125                 // Get a random string from the RNG
126                 $randomString = $this->getRngInstance()->randomString() . $this->createUuid();
127
128                 // Get config entry for salt length
129                 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
130
131                 // Keep only defined number of characters
132                 $this->salt = substr(sha1($randomString), -$length, $length);
133         }
134
135         /**
136          * Returns a UUID (Universal Unique IDentifier) if PECL extension uuid was
137          * found or an empty string it not.
138          *
139          * @return      $uuid   UUID with leading dash or empty string
140          */
141         public function createUuid () {
142                 // Init empty UUID
143                 $uuid = '';
144
145                 // Is the UUID extension loaded? (see pecl)
146                 if ((extension_loaded('uuid')) && (function_exists('uuid_create'))) {
147                         // Then add it as well
148                         $uuid = uuid_create();
149                 } // END - if
150
151                 // Return it
152                 return $uuid;
153         }
154
155         /**
156          * Hashes a string with salt and returns the hash. If an old previous hash
157          * is supplied the method will use the first X chars of that hash for hashing
158          * the password. This is useful if you want to check if password is identical
159          * for authorization purposes.
160          *
161          * @param       $str            Unhashed string
162          * @param       $oldHash        A hash from previous hashed string
163          * @param       $withFixed      Whether to include a fixed salt (not recommended in p2p applications)
164          * @return      $hashed         The hashed and salted string
165          */
166         public function hashString ($str, $oldHash = '', $withFixed = TRUE) {
167                 // Cast the string
168                 $str = (string) $str;
169
170                 // Default is the default salt ;-)
171                 $salt = $this->salt;
172
173                 // Is the old password set?
174                 if (!empty($oldHash)) {
175                         // Use the salt from hash, first get length
176                         $length = $this->getConfigInstance()->getConfigEntry('salt_length');
177
178                         // Then extract the X first characters from the hash as our salt
179                         $salt = substr($oldHash, 0, $length);
180                 } // END - if
181
182                 // Hash the password with salt
183                 //* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
184                 if ($withFixed === TRUE) {
185                         // Use additional fixed salt
186                         $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_extra_mask'),
187                                 $salt,
188                                 $this->getRngInstance()->getFixedSalt(),
189                                 $str
190                         ));
191                 } else {
192                         // Use salt+string to hash
193                         $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_normal_mask'),
194                                 $salt,
195                                 $str
196                         ));
197                 }
198
199                 // And return it
200                 return $hashed;
201         }
202
203         /**
204          * Encrypt the string with fixed salt
205          *
206          * @param       $str            The unencrypted string
207          * @param       $key            Optional key, if none provided, a random key will be generated
208          * @return      $encrypted      Encrypted string
209          */
210         public function encryptString ($str, $key = NULL) {
211                 // Encrypt the string through the stream
212                 $encrypted = $this->cryptoStreamInstance->encryptStream($str, $key);
213
214                 // Return the string
215                 return $encrypted;
216         }
217
218         /**
219          * Decrypt the string with fixed salt
220          *
221          * @param       $encrypted      Encrypted string
222          * @return      $str            The unencrypted string
223          */
224         public function decryptString ($encrypted) {
225                 // Encrypt the string through the stream
226                 $str = $this->cryptoStreamInstance->decryptStream($encrypted);
227
228                 // Return the string
229                 return $str;
230         }
231 }
232
233 // [EOF]
234 ?>