Streamable and for encryption added, CryptoHelper (a facade) rewritten to use streams
[core.git] / inc / classes / main / crypto / class_CryptoHelper.php
1 <?php
2 /**
3  * A helper class for cryptographical things like hashing passwords and so on
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 Core Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
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.
15  *
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.
20  *
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/>.
23  */
24 class CryptoHelper extends BaseFrameworkSystem implements Cryptable {
25         // Exception constants
26         const EXCEPTION_ENCRYPT_MISSING = 0x1f0;
27         const EXCEPTION_ENCRYPT_INVALID = 0x1f1;
28
29         /**
30          * An instance of this own clas
31          */
32         private static $selfInstance = null;
33
34         /**
35          * Instance of the random number generator
36          */
37         private $rngInstance = null;
38
39         /**
40          * Instance of the crypto stream
41          */
42         private $cryptoStreamInstance = null;
43
44         /**
45          * Salt for hashing operations
46          */
47         private $salt = '';
48
49         /**
50          * Protected constructor
51          *
52          * @return      void
53          */
54         protected function __construct () {
55                 // Call parent constructor
56                 parent::__construct(__CLASS__);
57
58                 // Clean up a little
59                 $this->removeNumberFormaters();
60                 $this->removeSystemArray();
61         }
62
63         /**
64          * Creates an instance of this class
65          *
66          * @return      $cryptoInstance         An instance of this crypto helper class
67          */
68         public final static function createCryptoHelper () {
69                 // Get a new instance
70                 $cryptoInstance = new CryptoHelper();
71
72                 // Initialize the hasher
73                 $cryptoInstance->initHasher();
74
75                 // Attach a crypto stream
76                 $cryptoInstance->attachCryptoStream();
77
78                 // Return the instance
79                 return $cryptoInstance;
80         }
81
82         /**
83          * Get a singleton instance of this class
84          *
85          * @return      $selfInstance   An instance of this crypto helper class
86          */
87         public final static function getInstance () {
88                 // Is no instance there?
89                 if (is_null(self::$selfInstance)) {
90                         // Then get a new one
91                         self::$selfInstance = self::createCryptoHelper();
92                 } // END - if
93
94                 // Return the instance
95                 return self::$selfInstance;
96         }
97
98         /**
99          * Attaches a crypto stream to this crypto helper by detecting loaded
100          * modules.
101          *
102          * @return      void
103          */
104         protected function attachCryptoStream () {
105                 // Do we have mcrypt loaded?
106                 if ($this->isPhpModuleLoaded('mcrypt')) {
107                         // Then use it
108                         $this->cryptoStreamInstance = ObjectFactory::createObjectByName('McryptStream', array($this->rngInstance()))
109                 } else {
110                         // If nothing works ...
111                         $this->cryptoStreamInstance = ObjectFactory::createObjectByName('NullCryptoStream');
112                 }
113         }
114
115         /**
116          * Initializes the hasher for different purposes.
117          *
118          * @return      void
119          */
120         protected function initHasher () {
121                 // Initialize the random number generator which is required by some crypto methods
122                 $this->rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
123
124                 // Generate a salt for the hasher
125                 $this->generateSalt();
126         }
127
128         /**
129          * Generates the salt based on configured length
130          *
131          * @return      void
132          */
133         private function generateSalt () {
134                 // Get a random string from the RNG
135                 $randomString = $this->rngInstance->randomString();
136
137                 // Get config entry for salt length
138                 $length = $this->getConfigInstance()->getConfigEntry('salt_length');
139
140                 // Keep only defined number of characters
141                 $this->salt = substr(sha1($randomString), -$length, $length);
142         }
143
144         /**
145          * Hashes a string with salt and returns the hash. If an old previous hash
146          * is supplied the method will use the first X chars of that hash for hashing
147          * the password. This is useful if you want to check if password is identical
148          * for authorization purposes.
149          *
150          * @param       $str            Unhashed string
151          * @param       $oldHash        A hash from previous hashed string
152          * @return      $hashed         The hashed and salted string
153          */
154         public function hashString ($str, $oldHash = '') {
155                 // Cast the string
156                 $str = (string) $str;
157
158                 // Default is the default salt ;-)
159                 $salt = $this->salt;
160
161                 // Is the old password set?
162                 if (!empty($oldHash)) {
163                         // Use the salt from hash, first get length
164                         $length = $this->getConfigInstance()->getConfigEntry('salt_length');
165
166                         // Then extract the X first characters from the hash as our salt
167                         $salt = substr($oldHash, 0, $length);
168                 } // END - if
169
170                 // Hash the password with salt
171                 //* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
172                 $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_mask'),
173                         $salt,
174                         $this->rngInstance->getFixedSalt(),
175                         $str
176                 ));
177
178                 // And return it
179                 return $hashed;
180         }
181
182         /**
183          * Encrypt the string with fixed salt
184          *
185          * @param       $str            The unencrypted string
186          * @return      $encrypted      Encrypted string
187          */
188         public function encryptString ($str) {
189                 // Encrypt the string through the stream
190                 $encryted = $this->cryptoStreamInstance->encryptStream($str);
191
192                 // Return the string
193                 return $encrypted;
194         }
195
196         /**
197          * Decrypt the string with fixed salt
198          *
199          * @param       $encrypted      Encrypted string
200          * @return      $str            The unencrypted string
201          */
202         public function decryptString ($encrypted) {
203                 // Encrypt the string through the stream
204                 $str = $this->cryptoStreamInstance->decryptStream($encrypted);
205
206                 // Return the string
207                 return $str;
208         }
209 }
210
211 // [EOF]
212 ?>