]> git.mxchange.org Git - core.git/blob - framework/main/classes/crypto/class_CryptoHelper.php
Continued:
[core.git] / framework / main / classes / crypto / class_CryptoHelper.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Helper\Crypto;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Crypto\Cryptable;
7 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
8 use Org\Mxchange\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 - 2020 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                 // @TODO Maybe rewrite this with DirectoryIterator, similar to Compressor thing?
105                 // Do we have openssl/mcrypt loaded?
106                 if ($this->isPhpExtensionLoaded('mcrypt')) {
107                         // Then use it
108                         $this->cryptoStreamInstance = ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Stream\Crypto\McryptStream', array($this->getRngInstance()));
109                 } elseif ($this->isPhpExtensionLoaded('openssl')) {
110                         // Then use it
111                         $this->cryptoStreamInstance = ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Stream\Crypto\OpenSslStream', array($this->getRngInstance()));
112                 } else {
113                         // If nothing works ...
114                         $this->cryptoStreamInstance = ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Stream\Crypto\NullCryptoStream');
115                 }
116         }
117
118         /**
119          * Initializes the hasher for different purposes.
120          *
121          * @return      void
122          */
123         protected function initHasher () {
124                 // Initialize the random number generator which is required by some crypto methods
125                 $this->setRngInstance(ObjectFactory::createObjectByConfiguredName('rng_class'));
126
127                 // Generate a salt for the hasher
128                 $this->generateSalt();
129         }
130
131         /**
132          * Generates the salt based on configured length
133          *
134          * @return      void
135          */
136         private function generateSalt () {
137                 // Get a random string from the RNG
138                 $randomString = $this->getRngInstance()->randomString() . $this->createUuid();
139
140                 // Get config entry for salt length
141                 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
142
143                 // Keep only defined number of characters
144                 $this->salt = substr(sha1($randomString), -$length, $length);
145         }
146
147         /**
148          * Returns a UUID (Universal Unique IDentifier) if PECL extension uuid was
149          * found or an empty string it not.
150          *
151          * @return      $uuid   UUID with leading dash or empty string
152          */
153         public function createUuid () {
154                 // Init empty UUID
155                 $uuid = '';
156
157                 // Is the UUID extension loaded and enabled? (see pecl)
158                 if ($this->getConfigInstance()->getConfigEntry('extension_uuid_loaded') === true) {
159                         // Then add it as well
160                         $uuid = uuid_create();
161                 } // END - if
162
163                 // Return it
164                 return $uuid;
165         }
166
167         /**
168          * Hashes a string with salt and returns the hash. If an old previous hash
169          * is supplied the method will use the first X chars of that hash for hashing
170          * the password. This is useful if you want to check if password is identical
171          * for authorization purposes.
172          *
173          * @param       $str            Unhashed string
174          * @param       $oldHash        A hash from previous hashed string
175          * @param       $withFixed      Whether to include a fixed salt (not recommended in p2p applications)
176          * @return      $hashed         The hashed and salted string
177          */
178         public function hashString ($str, $oldHash = '', $withFixed = true) {
179                 // Cast the string
180                 $str = (string) $str;
181
182                 // Default is the default salt ;-)
183                 $salt = $this->salt;
184
185                 // Is the old password set?
186                 if (!empty($oldHash)) {
187                         // Use the salt from hash, first get length
188                         $length = $this->getConfigInstance()->getConfigEntry('salt_length');
189
190                         // Then extract the X first characters from the hash as our salt
191                         $salt = substr($oldHash, 0, $length);
192                 } // END - if
193
194                 // Hash the password with salt
195                 //* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
196                 if ($withFixed === true) {
197                         // Use additional fixed salt
198                         $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_extra_mask'),
199                                 $salt,
200                                 $this->getRngInstance()->getFixedSalt(),
201                                 $str
202                         ));
203                 } else {
204                         // Use salt+string to hash
205                         $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_normal_mask'),
206                                 $salt,
207                                 $str
208                         ));
209                 }
210
211                 // And return it
212                 return $hashed;
213         }
214
215         /**
216          * Encrypt the string with fixed salt
217          *
218          * @param       $str            The unencrypted string
219          * @param       $key            Optional key, if none provided, a random key will be generated
220          * @return      $encrypted      Encrypted string
221          */
222         public function encryptString ($str, $key = NULL) {
223                 // Encrypt the string through the stream
224                 $encrypted = $this->cryptoStreamInstance->encryptStream($str, $key);
225
226                 // Return the string
227                 return $encrypted;
228         }
229
230         /**
231          * Decrypt the string with fixed salt
232          *
233          * @param       $encrypted      Encrypted string
234          * @return      $str            The unencrypted string
235          */
236         public function decryptString ($encrypted) {
237                 // Encrypt the string through the stream
238                 $str = $this->cryptoStreamInstance->decryptStream($encrypted);
239
240                 // Return the string
241                 return $str;
242         }
243
244 }