3 namespace Org\Mxchange\CoreFramework\Helper\Crypto;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Crypto\Cryptable;
8 use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
9 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
10 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
13 * A helper class for cryptographical things like hashing passwords and so on
15 * @author Roland Haeder <webmaster@shipsimu.org>
17 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
18 * @license GNU GPL 3.0 or any newer version
19 * @link http://www.shipsimu.org
21 * This program is free software: you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation, either version 3 of the License, or
24 * (at your option) any later version.
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <http://www.gnu.org/licenses/>.
34 class CryptoHelper extends BaseFrameworkSystem implements Cryptable {
35 // Exception constants
36 const EXCEPTION_ENCRYPT_MISSING = 0x1f0;
37 const EXCEPTION_ENCRYPT_INVALID = 0x1f1;
40 * An instance of this own clas
42 private static $selfInstance = NULL;
45 * Instance of the crypto stream
47 private $cryptoStreamInstance = NULL;
50 * Salt for hashing operations
57 private $rngInstance = NULL;
60 * Protected constructor
64 protected function __construct () {
65 // Call parent constructor
66 parent::__construct(__CLASS__);
70 * Creates an instance of this class
72 * @return $cryptoInstance An instance of this crypto helper class
74 public static final function createCryptoHelper () {
76 $cryptoInstance = new CryptoHelper();
78 // Initialize the hasher
79 $cryptoInstance->initHasher();
81 // Attach a crypto stream
82 $cryptoInstance->attachCryptoStream();
84 // Return the instance
85 return $cryptoInstance;
89 * Get a singleton instance of this class
91 * @return $selfInstance An instance of this crypto helper class
93 public static final function getSelfInstance () {
94 // Is no instance there?
95 if (is_null(self::$selfInstance)) {
97 self::$selfInstance = self::createCryptoHelper();
100 // Return the instance
101 return self::$selfInstance;
105 * Setter for RNG instance
107 * @param $rngInstance An instance of a random number generator (RNG)
110 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
111 $this->rngInstance = $rngInstance;
115 * Getter for RNG instance
117 * @return $rngInstance An instance of a random number generator (RNG)
119 public final function getRngInstance () {
120 return $this->rngInstance;
124 * Attaches a crypto stream to this crypto helper by detecting loaded
129 protected function attachCryptoStream () {
130 // @TODO Maybe rewrite this with DirectoryIterator, similar to Compressor thing?
131 // Do we have openssl/mcrypt loaded?
132 if ($this->isPhpExtensionLoaded('mcrypt')) {
134 $this->cryptoStreamInstance = ObjectFactory::createObjectByConfiguredName('crypto_mcrypt_stream_class', array($this->getRngInstance()));
135 } elseif ($this->isPhpExtensionLoaded('openssl')) {
137 $this->cryptoStreamInstance = ObjectFactory::createObjectByConfiguredName('crypto_openssl_stream_class', array($this->getRngInstance()));
139 // If nothing works ...
140 $this->cryptoStreamInstance = ObjectFactory::createObjectByConfiguredName('crypto_null_stream_class');
145 * Initializes the hasher for different purposes.
149 protected function initHasher () {
150 // Initialize the random number generator which is required by some crypto methods
151 $this->setRngInstance(ObjectFactory::createObjectByConfiguredName('rng_class'));
153 // Generate a salt for the hasher
154 $this->generateSalt();
158 * Generates the salt based on configured length
162 private function generateSalt () {
163 // Get a random string from the RNG
164 $randomString = $this->getRngInstance()->randomString() . $this->createUuid();
166 // Get config entry for salt length
167 $length = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('salt_length');
169 // Keep only defined number of characters
170 $this->salt = substr(sha1($randomString), -$length, $length);
174 * Returns a UUID (Universal Unique IDentifier) if PECL extension uuid was
175 * found or an empty string it not.
177 * @return $uuid UUID with leading dash or empty string
179 public function createUuid () {
183 // Is the UUID extension loaded and enabled? (see pecl)
184 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('extension_uuid_loaded') === true) {
185 // Then add it as well
186 $uuid = uuid_create();
194 * Hashes a string with salt and returns the hash. If an old previous hash
195 * is supplied the method will use the first X chars of that hash for hashing
196 * the password. This is useful if you want to check if password is identical
197 * for authorization purposes.
199 * @param $str Unhashed string
200 * @param $oldHash A hash from previous hashed string
201 * @param $withFixed Whether to include a fixed salt (not recommended in p2p applications)
202 * @return $hashed The hashed and salted string
204 public function hashString ($str, $oldHash = '', $withFixed = true) {
206 $str = (string) $str;
208 // Default is the default salt ;-)
211 // Is the old password set?
212 if (!empty($oldHash)) {
213 // Use the salt from hash, first get length
214 $length = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('salt_length');
216 // Then extract the X first characters from the hash as our salt
217 $salt = substr($oldHash, 0, $length);
220 // Hash the password with salt
221 //* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
222 if ($withFixed === true) {
223 // Use additional fixed salt
224 $hashed = $salt . md5(sprintf(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('hash_extra_mask'),
226 $this->getRngInstance()->getFixedSalt(),
230 // Use salt+string to hash
231 $hashed = $salt . md5(sprintf(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('hash_normal_mask'),
242 * Encrypt the string with fixed salt
244 * @param $str The unencrypted string
245 * @param $key Optional key, if none provided, a random key will be generated
246 * @return $encrypted Encrypted string
248 public function encryptString ($str, $key = NULL) {
249 // Encrypt the string through the stream
250 $encrypted = $this->cryptoStreamInstance->encryptStream($str, $key);
257 * Decrypt the string with fixed salt
259 * @param $encrypted Encrypted string
260 * @return $str The unencrypted string
262 public function decryptString ($encrypted) {
263 // Encrypt the string through the stream
264 $str = $this->cryptoStreamInstance->decryptStream($encrypted);