3 namespace CoreFramework\Helper\Crypto;
5 // Import framework stuff
6 use CoreFramework\Crypto\Cryptable;
7 use CoreFramework\Factory\ObjectFactory;
8 use 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 - 2017 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 // Do we have mcrypt loaded?
105 if ($this->isPhpExtensionLoaded('mcrypt')) {
107 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('McryptStream', array($this->getRngInstance()));
109 // If nothing works ...
110 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('NullCryptoStream');
115 * Initializes the hasher for different purposes.
119 protected function initHasher () {
120 // Initialize the random number generator which is required by some crypto methods
121 $this->setRngInstance(ObjectFactory::createObjectByConfiguredName('rng_class'));
123 // Generate a salt for the hasher
124 $this->generateSalt();
128 * Generates the salt based on configured length
132 private function generateSalt () {
133 // Get a random string from the RNG
134 $randomString = $this->getRngInstance()->randomString() . $this->createUuid();
136 // Get config entry for salt length
137 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
139 // Keep only defined number of characters
140 $this->salt = substr(sha1($randomString), -$length, $length);
144 * Returns a UUID (Universal Unique IDentifier) if PECL extension uuid was
145 * found or an empty string it not.
147 * @return $uuid UUID with leading dash or empty string
149 public function createUuid () {
153 // Is the UUID extension loaded and enabled? (see pecl)
154 if ($this->getConfigInstance()->getConfigEntry('extension_uuid_loaded') === TRUE) {
155 // Then add it as well
156 $uuid = uuid_create();
164 * Hashes a string with salt and returns the hash. If an old previous hash
165 * is supplied the method will use the first X chars of that hash for hashing
166 * the password. This is useful if you want to check if password is identical
167 * for authorization purposes.
169 * @param $str Unhashed string
170 * @param $oldHash A hash from previous hashed string
171 * @param $withFixed Whether to include a fixed salt (not recommended in p2p applications)
172 * @return $hashed The hashed and salted string
174 public function hashString ($str, $oldHash = '', $withFixed = TRUE) {
176 $str = (string) $str;
178 // Default is the default salt ;-)
181 // Is the old password set?
182 if (!empty($oldHash)) {
183 // Use the salt from hash, first get length
184 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
186 // Then extract the X first characters from the hash as our salt
187 $salt = substr($oldHash, 0, $length);
190 // Hash the password with salt
191 //* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
192 if ($withFixed === TRUE) {
193 // Use additional fixed salt
194 $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_extra_mask'),
196 $this->getRngInstance()->getFixedSalt(),
200 // Use salt+string to hash
201 $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_normal_mask'),
212 * Encrypt the string with fixed salt
214 * @param $str The unencrypted string
215 * @param $key Optional key, if none provided, a random key will be generated
216 * @return $encrypted Encrypted string
218 public function encryptString ($str, $key = NULL) {
219 // Encrypt the string through the stream
220 $encrypted = $this->cryptoStreamInstance->encryptStream($str, $key);
227 * Decrypt the string with fixed salt
229 * @param $encrypted Encrypted string
230 * @return $str The unencrypted string
232 public function decryptString ($encrypted) {
233 // Encrypt the string through the stream
234 $str = $this->cryptoStreamInstance->decryptStream($encrypted);