3 namespace CoreFramework\Helper\Crypto;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Object\BaseFrameworkSystem;
10 * A helper class for cryptographical things like hashing passwords and so on
12 * @author Roland Haeder <webmaster@shipsimu.org>
14 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
15 * @license GNU GPL 3.0 or any newer version
16 * @link http://www.shipsimu.org
18 * This program is free software: you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation, either version 3 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 class CryptoHelper extends BaseFrameworkSystem implements Cryptable {
32 // Exception constants
33 const EXCEPTION_ENCRYPT_MISSING = 0x1f0;
34 const EXCEPTION_ENCRYPT_INVALID = 0x1f1;
37 * An instance of this own clas
39 private static $selfInstance = NULL;
42 * Instance of the crypto stream
44 private $cryptoStreamInstance = NULL;
47 * Salt for hashing operations
52 * Protected constructor
56 protected function __construct () {
57 // Call parent constructor
58 parent::__construct(__CLASS__);
62 * Creates an instance of this class
64 * @return $cryptoInstance An instance of this crypto helper class
66 public static final function createCryptoHelper () {
68 $cryptoInstance = new CryptoHelper();
70 // Initialize the hasher
71 $cryptoInstance->initHasher();
73 // Attach a crypto stream
74 $cryptoInstance->attachCryptoStream();
76 // Return the instance
77 return $cryptoInstance;
81 * Get a singleton instance of this class
83 * @return $selfInstance An instance of this crypto helper class
85 public static final function getSelfInstance () {
86 // Is no instance there?
87 if (is_null(self::$selfInstance)) {
89 self::$selfInstance = self::createCryptoHelper();
92 // Return the instance
93 return self::$selfInstance;
97 * Attaches a crypto stream to this crypto helper by detecting loaded
102 protected function attachCryptoStream () {
103 // Do we have mcrypt loaded?
104 if ($this->isPhpExtensionLoaded('mcrypt')) {
106 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('McryptStream', array($this->getRngInstance()));
108 // If nothing works ...
109 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('NullCryptoStream');
114 * Initializes the hasher for different purposes.
118 protected function initHasher () {
119 // Initialize the random number generator which is required by some crypto methods
120 $this->setRngInstance(ObjectFactory::createObjectByConfiguredName('rng_class'));
122 // Generate a salt for the hasher
123 $this->generateSalt();
127 * Generates the salt based on configured length
131 private function generateSalt () {
132 // Get a random string from the RNG
133 $randomString = $this->getRngInstance()->randomString() . $this->createUuid();
135 // Get config entry for salt length
136 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
138 // Keep only defined number of characters
139 $this->salt = substr(sha1($randomString), -$length, $length);
143 * Returns a UUID (Universal Unique IDentifier) if PECL extension uuid was
144 * found or an empty string it not.
146 * @return $uuid UUID with leading dash or empty string
148 public function createUuid () {
152 // Is the UUID extension loaded and enabled? (see pecl)
153 if ($this->getConfigInstance()->getConfigEntry('extension_uuid_loaded') === TRUE) {
154 // Then add it as well
155 $uuid = uuid_create();
163 * Hashes a string with salt and returns the hash. If an old previous hash
164 * is supplied the method will use the first X chars of that hash for hashing
165 * the password. This is useful if you want to check if password is identical
166 * for authorization purposes.
168 * @param $str Unhashed string
169 * @param $oldHash A hash from previous hashed string
170 * @param $withFixed Whether to include a fixed salt (not recommended in p2p applications)
171 * @return $hashed The hashed and salted string
173 public function hashString ($str, $oldHash = '', $withFixed = TRUE) {
175 $str = (string) $str;
177 // Default is the default salt ;-)
180 // Is the old password set?
181 if (!empty($oldHash)) {
182 // Use the salt from hash, first get length
183 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
185 // Then extract the X first characters from the hash as our salt
186 $salt = substr($oldHash, 0, $length);
189 // Hash the password with salt
190 //* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
191 if ($withFixed === TRUE) {
192 // Use additional fixed salt
193 $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_extra_mask'),
195 $this->getRngInstance()->getFixedSalt(),
199 // Use salt+string to hash
200 $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_normal_mask'),
211 * Encrypt the string with fixed salt
213 * @param $str The unencrypted string
214 * @param $key Optional key, if none provided, a random key will be generated
215 * @return $encrypted Encrypted string
217 public function encryptString ($str, $key = NULL) {
218 // Encrypt the string through the stream
219 $encrypted = $this->cryptoStreamInstance->encryptStream($str, $key);
226 * Decrypt the string with fixed salt
228 * @param $encrypted Encrypted string
229 * @return $str The unencrypted string
231 public function decryptString ($encrypted) {
232 // Encrypt the string through the stream
233 $str = $this->cryptoStreamInstance->decryptStream($encrypted);