3 * A helper class for cryptographical things like hashing passwords and so on
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class CryptoHelper extends BaseFrameworkSystem implements Cryptable {
25 // Exception constants
26 const EXCEPTION_ENCRYPT_MISSING = 0x1f0;
27 const EXCEPTION_ENCRYPT_INVALID = 0x1f1;
30 * An instance of this own clas
32 private static $selfInstance = null;
35 * Instance of the crypto stream
37 private $cryptoStreamInstance = null;
40 * Salt for hashing operations
45 * Protected constructor
49 protected function __construct () {
50 // Call parent constructor
51 parent::__construct(__CLASS__);
55 * Creates an instance of this class
57 * @return $cryptoInstance An instance of this crypto helper class
59 public static final function createCryptoHelper () {
61 $cryptoInstance = new CryptoHelper();
63 // Initialize the hasher
64 $cryptoInstance->initHasher();
66 // Attach a crypto stream
67 $cryptoInstance->attachCryptoStream();
69 // Return the instance
70 return $cryptoInstance;
74 * Get a singleton instance of this class
76 * @return $selfInstance An instance of this crypto helper class
78 public static final function getInstance () {
79 // Is no instance there?
80 if (is_null(self::$selfInstance)) {
82 self::$selfInstance = self::createCryptoHelper();
85 // Return the instance
86 return self::$selfInstance;
90 * Attaches a crypto stream to this crypto helper by detecting loaded
95 protected function attachCryptoStream () {
96 // Do we have mcrypt loaded?
97 if ($this->isPhpExtensionLoaded('mcrypt')) {
99 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('McryptStream', array($this->getRngInstance()));
101 // If nothing works ...
102 $this->cryptoStreamInstance = ObjectFactory::createObjectByName('NullCryptoStream');
107 * Initializes the hasher for different purposes.
111 protected function initHasher () {
112 // Initialize the random number generator which is required by some crypto methods
113 $this->setRngInstance(ObjectFactory::createObjectByConfiguredName('rng_class'));
115 // Generate a salt for the hasher
116 $this->generateSalt();
120 * Generates the salt based on configured length
124 private function generateSalt () {
125 // Get a random string from the RNG
126 $randomString = $this->getRngInstance()->randomString();
128 // Get config entry for salt length
129 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
131 // Keep only defined number of characters
132 $this->salt = substr(sha1($randomString), -$length, $length);
136 * Hashes a string with salt and returns the hash. If an old previous hash
137 * is supplied the method will use the first X chars of that hash for hashing
138 * the password. This is useful if you want to check if password is identical
139 * for authorization purposes.
141 * @param $str Unhashed string
142 * @param $oldHash A hash from previous hashed string
143 * @return $hashed The hashed and salted string
145 public function hashString ($str, $oldHash = '') {
147 $str = (string) $str;
149 // Default is the default salt ;-)
152 // Is the old password set?
153 if (!empty($oldHash)) {
154 // Use the salt from hash, first get length
155 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
157 // Then extract the X first characters from the hash as our salt
158 $salt = substr($oldHash, 0, $length);
161 // Hash the password with salt
162 //* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
163 $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_mask'),
165 $this->getRngInstance()->getFixedSalt(),
174 * Encrypt the string with fixed salt
176 * @param $str The unencrypted string
177 * @param $key Optional key, if none provided, a random key will be generated
178 * @return $encrypted Encrypted string
180 public function encryptString ($str, $key = null) {
181 // Encrypt the string through the stream
182 $encrypted = $this->cryptoStreamInstance->encryptStream($str, $key);
189 * Decrypt the string with fixed salt
191 * @param $encrypted Encrypted string
192 * @return $str The unencrypted string
194 public function decryptString ($encrypted) {
195 // Encrypt the string through the stream
196 $str = $this->cryptoStreamInstance->decryptStream($encrypted);