3 namespace CoreFramework\Helper\Crypto;
5 // Import framework stuff
6 use CoreFramework\Object\BaseFrameworkSystem;
9 * A helper class for cryptographical things like hashing passwords and so on
11 * @author Roland Haeder <webmaster@shipsimu.org>
13 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
14 * @license GNU GPL 3.0 or any newer version
15 * @link http://www.shipsimu.org
17 * This program is free software: you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation, either version 3 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 class CryptoHelper extends BaseFrameworkSystem implements Cryptable {
31 // Exception constants
32 const EXCEPTION_ENCRYPT_MISSING = 0x1f0;
33 const EXCEPTION_ENCRYPT_INVALID = 0x1f1;
36 * An instance of this own clas
38 private static $selfInstance = NULL;
41 * Instance of the crypto stream
43 private $cryptoStreamInstance = NULL;
46 * Salt for hashing operations
51 * Protected constructor
55 protected function __construct () {
56 // Call parent constructor
57 parent::__construct(__CLASS__);
61 * Creates an instance of this class
63 * @return $cryptoInstance An instance of this crypto helper class
65 public static final function createCryptoHelper () {
67 $cryptoInstance = new CryptoHelper();
69 // Initialize the hasher
70 $cryptoInstance->initHasher();
72 // Attach a crypto stream
73 $cryptoInstance->attachCryptoStream();
75 // Return the instance
76 return $cryptoInstance;
80 * Get a singleton instance of this class
82 * @return $selfInstance An instance of this crypto helper class
84 public static final function getSelfInstance () {
85 // Is no instance there?
86 if (is_null(self::$selfInstance)) {
88 self::$selfInstance = self::createCryptoHelper();
91 // Return the instance
92 return self::$selfInstance;
96 * Attaches a crypto stream to this crypto helper by detecting loaded
101 protected function attachCryptoStream () {
102 // Do we have mcrypt loaded?
103 if ($this->isPhpExtensionLoaded('mcrypt')) {
105 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('McryptStream', array($this->getRngInstance()));
107 // If nothing works ...
108 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('NullCryptoStream');
113 * Initializes the hasher for different purposes.
117 protected function initHasher () {
118 // Initialize the random number generator which is required by some crypto methods
119 $this->setRngInstance(ObjectFactory::createObjectByConfiguredName('rng_class'));
121 // Generate a salt for the hasher
122 $this->generateSalt();
126 * Generates the salt based on configured length
130 private function generateSalt () {
131 // Get a random string from the RNG
132 $randomString = $this->getRngInstance()->randomString() . $this->createUuid();
134 // Get config entry for salt length
135 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
137 // Keep only defined number of characters
138 $this->salt = substr(sha1($randomString), -$length, $length);
142 * Returns a UUID (Universal Unique IDentifier) if PECL extension uuid was
143 * found or an empty string it not.
145 * @return $uuid UUID with leading dash or empty string
147 public function createUuid () {
151 // Is the UUID extension loaded and enabled? (see pecl)
152 if ($this->getConfigInstance()->getConfigEntry('extension_uuid_loaded') === TRUE) {
153 // Then add it as well
154 $uuid = uuid_create();
162 * Hashes a string with salt and returns the hash. If an old previous hash
163 * is supplied the method will use the first X chars of that hash for hashing
164 * the password. This is useful if you want to check if password is identical
165 * for authorization purposes.
167 * @param $str Unhashed string
168 * @param $oldHash A hash from previous hashed string
169 * @param $withFixed Whether to include a fixed salt (not recommended in p2p applications)
170 * @return $hashed The hashed and salted string
172 public function hashString ($str, $oldHash = '', $withFixed = TRUE) {
174 $str = (string) $str;
176 // Default is the default salt ;-)
179 // Is the old password set?
180 if (!empty($oldHash)) {
181 // Use the salt from hash, first get length
182 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
184 // Then extract the X first characters from the hash as our salt
185 $salt = substr($oldHash, 0, $length);
188 // Hash the password with salt
189 //* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
190 if ($withFixed === TRUE) {
191 // Use additional fixed salt
192 $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_extra_mask'),
194 $this->getRngInstance()->getFixedSalt(),
198 // Use salt+string to hash
199 $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_normal_mask'),
210 * Encrypt the string with fixed salt
212 * @param $str The unencrypted string
213 * @param $key Optional key, if none provided, a random key will be generated
214 * @return $encrypted Encrypted string
216 public function encryptString ($str, $key = NULL) {
217 // Encrypt the string through the stream
218 $encrypted = $this->cryptoStreamInstance->encryptStream($str, $key);
225 * Decrypt the string with fixed salt
227 * @param $encrypted Encrypted string
228 * @return $str The unencrypted string
230 public function decryptString ($encrypted) {
231 // Encrypt the string through the stream
232 $str = $this->cryptoStreamInstance->decryptStream($encrypted);