Graphical code CAPTCHA partly finished, crypto class supports encryption/decryption...
[shipsimu.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, this is free software
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         /**
26          * An instance of this own clas
27          */
28         private static $selfInstance = null;
29
30         /**
31          * Instance of the random number generator
32          */
33         private $rngInstance = null;
34
35         /**
36          * Salt for hashing operations
37          */
38         private $salt = "";
39
40         /**
41          * Protected constructor
42          *
43          * @return      void
44          */
45         protected function __construct () {
46                 // Call parent constructor
47                 parent::__construct(__CLASS__);
48
49                 // Set part description
50                 $this->setObjectDescription("Cryptographical helper");
51
52                 // Create unique ID number
53                 $this->generateUniqueId();
54
55                 // Clean up a little
56                 $this->removeNumberFormaters();
57                 $this->removeSystemArray();
58         }
59
60         /**
61          * Creates an instance of this class
62          *
63          * @return      $cryptoInstance         An instance of this crypto helper class
64          */
65         public final static function createCryptoHelper () {
66                 // Get a new instance
67                 $cryptoInstance = new CryptoHelper();
68
69                 // Initialize the hasher
70                 $cryptoInstance->initHasher();
71
72                 // Return the instance
73                 return $cryptoInstance;
74         }
75
76         /**
77          * Get a singleton instance of this class
78          *
79          * @return      $selfInstance   An instance of this crypto helper class
80          */
81         public final static function getInstance () {
82                 // Is no instance there?
83                 if (is_null(self::$selfInstance)) {
84                         // Then get a new one
85                         self::$selfInstance = self::createCryptoHelper();
86                 }
87
88                 // Return the instance
89                 return self::$selfInstance;
90         }
91
92         /**
93          * Initializes the hasher for different purposes.
94          *
95          * @return      void
96          */
97         protected function initHasher () {
98                 // Initialize the random number generator which is required by some crypto methods
99                 $this->rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
100
101                 // Generate a salt for the hasher
102                 $this->generateSalt();
103         }
104
105         /**
106          * Generates the salt based on configured length
107          *
108          * @return      void
109          */
110         private function generateSalt () {
111                 // Get a random string from the RNG
112                 $randomString = $this->rngInstance->randomString();
113
114                 // Get config entry for salt length
115                 $length = $this->getConfigInstance()->readConfig('salt_length');
116
117                 // Keep only defined number of characters
118                 $this->salt = substr(sha1($randomString), -$length, $length);
119         }
120
121         /**
122          * Hashes a string with salt and returns the hash. If an old previous hash
123          * is supplied the method will use the first X chars of that hash for hashing
124          * the password. This is useful if you want to check if the password is
125          * identical for authorization purposes.
126          *
127          * @param       $str            Unhashed string
128          * @param       $oldHash        A hash from previous hashed string
129          * @return      $hashed         The hashed and salted string
130          */
131         public function hashString ($str, $oldHash = "") {
132                 // Cast the string
133                 $str = (string) $str;
134
135                 // Is the old password set?
136                 if (empty($oldHash)) {
137                         // No, then use the current salt
138                         $salt = $this->salt;
139                 } else {
140                         // Use the salt from hash, first get length
141                         $length = $this->getConfigInstance()->readConfig('salt_length');
142
143                         // Then extract the X first characters from the hash as our salt
144                         $salt = substr($oldHash, 0, $length);
145                 }
146
147                 // Hash the password with salt
148                 //* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
149                 $hashed = $salt . md5(sprintf($this->getConfigInstance()->readConfig('hash_mask'),
150                         $salt,
151                         $this->rngInstance->getFixedSalt(),
152                         $str
153                 ));
154
155                 // And return it
156                 return $hashed;
157         }
158
159         /**
160          * Encrypt the string with fixed salt
161          *
162          * @param       $str            The unencrypted string
163          * @return      $encrypted      Encrypted string
164          */
165         public function encryptString ($str) {
166                 // Init crypto module
167                 $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
168                 $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
169
170                 // Get key
171                 $key = md5($this->rngInstance->getFixedSalt());
172
173                 // Encrypt the string
174                 $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $str, MCRYPT_MODE_ECB, $iv);
175
176                 // Return the string
177                 return $encrypted;
178         }
179
180         /**
181          * Decrypt the string with fixed salt
182          *
183          * @param       $encrypted      Encrypted string
184          * @return      $str            The unencrypted string
185          */
186         public function decryptString ($encrypted) {
187                 // Init crypto module
188                 $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
189                 $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
190
191                 // Get key
192                 $key = md5($this->rngInstance->getFixedSalt());
193
194                 // Encrypt the string
195                 $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_ECB, $iv);
196
197                 // Trim trailing nulls away
198                 $str = rtrim($str, "\0");
199
200                 // Return the string
201                 return $str;
202         }
203 }
204
205 // [EOF]
206 ?>