3 namespace Org\Mxchange\CoreFramework\Helper\Crypto;
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;
11 * A helper class for cryptographical things like hashing passwords and so on
13 * @author Roland Haeder <webmaster@shipsimu.org>
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
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.
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.
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/>.
32 class CryptoHelper extends BaseFrameworkSystem implements Cryptable {
33 // Exception constants
34 const EXCEPTION_ENCRYPT_MISSING = 0x1f0;
35 const EXCEPTION_ENCRYPT_INVALID = 0x1f1;
38 * An instance of this own clas
40 private static $selfInstance = NULL;
43 * Instance of the crypto stream
45 private $cryptoStreamInstance = NULL;
48 * Salt for hashing operations
53 * Protected constructor
57 protected function __construct () {
58 // Call parent constructor
59 parent::__construct(__CLASS__);
63 * Creates an instance of this class
65 * @return $cryptoInstance An instance of this crypto helper class
67 public static final function createCryptoHelper () {
69 $cryptoInstance = new CryptoHelper();
71 // Initialize the hasher
72 $cryptoInstance->initHasher();
74 // Attach a crypto stream
75 $cryptoInstance->attachCryptoStream();
77 // Return the instance
78 return $cryptoInstance;
82 * Get a singleton instance of this class
84 * @return $selfInstance An instance of this crypto helper class
86 public static final function getSelfInstance () {
87 // Is no instance there?
88 if (is_null(self::$selfInstance)) {
90 self::$selfInstance = self::createCryptoHelper();
93 // Return the instance
94 return self::$selfInstance;
98 * Attaches a crypto stream to this crypto helper by detecting loaded
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')) {
108 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Stream\Crypto\McryptStream', array($this->getRngInstance()));
109 } elseif ($this->isPhpExtensionLoaded('openssl')) {
111 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Stream\Crypto\OpenSslStream', array($this->getRngInstance()));
113 // If nothing works ...
114 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Stream\Crypto\NullCryptoStream');
119 * Initializes the hasher for different purposes.
123 protected function initHasher () {
124 // Initialize the random number generator which is required by some crypto methods
125 $this->setRngInstance(ObjectFactory::createObjectByConfiguredName('rng_class'));
127 // Generate a salt for the hasher
128 $this->generateSalt();
132 * Generates the salt based on configured length
136 private function generateSalt () {
137 // Get a random string from the RNG
138 $randomString = $this->getRngInstance()->randomString() . $this->createUuid();
140 // Get config entry for salt length
141 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
143 // Keep only defined number of characters
144 $this->salt = substr(sha1($randomString), -$length, $length);
148 * Returns a UUID (Universal Unique IDentifier) if PECL extension uuid was
149 * found or an empty string it not.
151 * @return $uuid UUID with leading dash or empty string
153 public function createUuid () {
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();
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.
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
178 public function hashString ($str, $oldHash = '', $withFixed = true) {
180 $str = (string) $str;
182 // Default is the default salt ;-)
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');
190 // Then extract the X first characters from the hash as our salt
191 $salt = substr($oldHash, 0, $length);
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'),
200 $this->getRngInstance()->getFixedSalt(),
204 // Use salt+string to hash
205 $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_normal_mask'),
216 * Encrypt the string with fixed salt
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
222 public function encryptString ($str, $key = NULL) {
223 // Encrypt the string through the stream
224 $encrypted = $this->cryptoStreamInstance->encryptStream($str, $key);
231 * Decrypt the string with fixed salt
233 * @param $encrypted Encrypted string
234 * @return $str The unencrypted string
236 public function decryptString ($encrypted) {
237 // Encrypt the string through the stream
238 $str = $this->cryptoStreamInstance->decryptStream($encrypted);