]> git.mxchange.org Git - shipsimu.git/commitdiff
Crypto helper and RNG added (weak!)
authorRoland Häder <roland@mxchange.org>
Sun, 8 Jun 2008 13:02:45 +0000 (13:02 +0000)
committerRoland Häder <roland@mxchange.org>
Sun, 8 Jun 2008 13:02:45 +0000 (13:02 +0000)
.gitattributes
application/ship-simu/main/registration/class_ShipSimuRegistration.php
inc/classes/main/crypto/.htaccess [new file with mode: 0644]
inc/classes/main/crypto/class_CryptoHelper.php [new file with mode: 0644]
inc/classes/main/database/databases/class_LocalFileDatabase.php
inc/classes/main/request/class_HttpRequest.php
inc/classes/main/rng/.htaccess [new file with mode: 0644]
inc/classes/main/rng/class_RandomNumberGenerator.php [new file with mode: 0644]
inc/classes/middleware/database/class_DatabaseConnection.php
inc/config.php

index 3f3f717017125c3b5a5529de65e2e1440e224cfc..0490db4c047590ebe2c23859f56b2ccf37ecc433 100644 (file)
@@ -304,6 +304,8 @@ inc/classes/main/controller/form/.htaccess -text
 inc/classes/main/controller/form/class_WebDoFormController.php -text
 inc/classes/main/criteria/.htaccess -text
 inc/classes/main/criteria/class_SearchCriteria.php -text
+inc/classes/main/crypto/.htaccess -text
+inc/classes/main/crypto/class_CryptoHelper.php -text
 inc/classes/main/database/.htaccess -text
 inc/classes/main/database/class_ -text
 inc/classes/main/database/class_BaseDatabaseFrontend.php -text
@@ -370,6 +372,8 @@ inc/classes/main/response/.htaccess -text
 inc/classes/main/response/class_HttpResponse.php -text
 inc/classes/main/result/.htaccess -text
 inc/classes/main/result/class_DatabaseResult.php -text
+inc/classes/main/rng/.htaccess -text
+inc/classes/main/rng/class_RandomNumberGenerator.php -text
 inc/classes/main/template/.htaccess -text
 inc/classes/main/template/class_TemplateEngine.php -text
 inc/classes/main/user/.htaccess -text
index dd5ef73d611210d964ac2573b9e053b4b979d5f8..ff3a45a34a798b39f8d22e3bd582b671b43de3ed 100644 (file)
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
  */
 class ShipSimuRegistration extends BaseRegistration {
+       /**
+        * Hashed password
+        */
+       private $hashedPassword = "";
+
        /**
         * Private constructor
         *
@@ -52,14 +57,20 @@ class ShipSimuRegistration extends BaseRegistration {
        }
 
        /**
-        * Encrypt the given request key or throws an exception if the key was not
+        * Encrypt the given request key or throw an exception if the key was not
         * found in the request
         *
         * @param       $requestKey             Key in request class
         * @return      void
         */
        public function encryptPassword ($requestKey) {
-               $this->partialStub(sprintf("requestKey=%s", $requestKey));
+               // Check if the password is found in the request
+               if ($this->getRequestInstance()->isRequestElementSet($requestKey)) {
+                       // So encrypt the password and store it for later usage in
+                       // the request
+                       $this->hashedPassword = ObjectFactory::createObjectByConfiguredName('crypto_heler')->hashPassword($this->getRequestInstance()->getRequestElement($requestKey));
+                       $this->getRequestInstance()->setRequestElement('pass_hash', $this->hashedPassword);
+               }
        }
 
        /**
diff --git a/inc/classes/main/crypto/.htaccess b/inc/classes/main/crypto/.htaccess
new file mode 100644 (file)
index 0000000..3a42882
--- /dev/null
@@ -0,0 +1 @@
+Deny from all
diff --git a/inc/classes/main/crypto/class_CryptoHelper.php b/inc/classes/main/crypto/class_CryptoHelper.php
new file mode 100644 (file)
index 0000000..5652b89
--- /dev/null
@@ -0,0 +1,123 @@
+<?php
+/**
+ * A helper class for cryptographical things like hashing passwords and so on
+ *
+ * @author             Roland Haeder <webmaster@ship-simu.org>
+ * @version            0.3.0
+ * @copyright  Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license            GNU GPL 3.0 or any newer version
+ * @link               http://www.mxchange.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+class CryptoHelper extends BaseFrameworkSystem {
+       /**
+        * An instance of this own clas
+        */
+       private static $selfInstance = null;
+
+       /**
+        * Instance of the random number generator
+        */
+       private $rngInstance = null;
+
+       /**
+        * Salt for hashing operations
+        */
+       private $salt = "";
+
+       /**
+        * Private constructor
+        *
+        * @return      void
+        */
+       protected function __construct () {
+               // Call parent constructor
+               parent::__construct(__CLASS__);
+
+               // Set part description
+               $this->setObjectDescription("Cryptographical helper");
+
+               // Create unique ID number
+               $this->createUniqueID();
+
+               // Clean up a little
+               $this->removeNumberFormaters();
+               $this->removeSystemArray();
+       }
+
+       /**
+        * Creates an instance of this class
+        *
+        * @return      $cryptoInstance         An instance of this crypto helper class
+        */
+       public final static function createCryptoHelper () {
+               // Get a new instance
+               $cryptoInstance = self::getInstance();
+
+               // Initialize the hasher
+               $cryptoInstance->initHasher();
+
+               // Return the instance
+               return $cryptoInstance;
+       }
+
+       /**
+        * Get a singleton instance of this class
+        *
+        * @return      $selfInstance   An instance of this crypto helper class
+        */
+       public final static function getInstance () {
+               // Is no instance there?
+               if (is_null(self::$selfInstance)) {
+                       // Then get a new one
+                       self::$selfInstance = new CryptoHelper();
+               }
+
+               // Return the instance
+               return self::$selfInstance;
+       }
+
+       /**
+        * Initializes the hasher for different purposes.
+        *
+        * @return      void
+        */
+       protected function initHasher () {
+               // Initialize the random number generator which is required by some crypto methods
+               $this->rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
+
+               // Generate a salt for the hasher
+               $this->generateSalt();
+       }
+
+       /**
+        * Generates the salt based on configured length
+        *
+        * @return      void
+        */
+       private function generateSalt () {
+               // Get a random string from the RNG
+               $randomString = $this->rngInstance->makeRandomString();
+
+               // Get config entry for salt length
+               $length = $this->getConfigInstance()->readConfig('salt_length');
+
+               // Keep only defined number of characters
+               $this->salt = substr($randomString, -$length, $length);
+       }
+}
+
+// [EOF]
+?>
index 9590b62a7e18b241c7c16df15535e64dd0120035..e7227015a142ead96147ae9e6ed256d8dc5df6a1 100644 (file)
@@ -86,10 +86,10 @@ class LocalFileDatabase extends BaseDatabaseFrontend implements DatabaseFrontend
         * Create an object of LocalFileDatabase and set the save path for local files.
         * This method also validates the given file path.
         *
-        * @param               $savePath                                       The local file path string
-        * @param               $ioInstance                             The input/output handler. This
-        *                                                                      should be FileIoHandler
-        * @return      $dbInstance                             An instance of LocalFileDatabase
+        * @param       $savePath               The local file path string
+        * @param       $ioInstance             The input/output handler. This
+        *                                                      should be FileIoHandler
+        * @return      $dbInstance             An instance of LocalFileDatabase
         */
        public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
                // Get an instance
@@ -151,7 +151,7 @@ class LocalFileDatabase extends BaseDatabaseFrontend implements DatabaseFrontend
         * Saves a given object to the local file system by serializing and
         * transparently compressing it
         *
-        * @param               $object                         The object we shall save to the local file system
+        * @param       $object                                 The object we shall save to the local file system
         * @return      void
         * @throws      NullPointerException    If the object instance is null
         * @throws      NoObjectException               If the parameter $object is not
@@ -186,7 +186,7 @@ class LocalFileDatabase extends BaseDatabaseFrontend implements DatabaseFrontend
        /**
         * Get a serialized string from the given object
         *
-        * @param               $object         The object we want to serialize and transparently
+        * @param       $object         The object we want to serialize and transparently
         *                                              compress
         * @return      $serialized     A string containing the serialzed/compressed object
         * @see         ObjectLimits    An object holding limition information
@@ -218,12 +218,12 @@ class LocalFileDatabase extends BaseDatabaseFrontend implements DatabaseFrontend
         * Analyses if a unique ID has already been used or not by search in the
         * local database folder.
         *
-        * @param               $uniqueID               A unique ID number which shall be checked
-        *                                              before it will be used
-        * @param               $inConstructor  If we got called in a de/con-structor or
-        *                                              from somewhere else
+        * @param       $uniqueID               A unique ID number which shall be checked
+        *                                                      before it will be used
+        * @param       $inConstructor  If we got called in a de/con-structor or
+        *                                                      from somewhere else
         * @return      $isUnused               true    = The unique ID was not found in the database,
-        *                                              false = It is already in use by an other object
+        *                                                      false = It is already in use by an other object
         * @throws      NoArrayCreatedException If explode() fails to create an array
         * @throws      InvalidArrayCountException      If the array contains less or
         *                                                                      more than two elements
index b95bab1bbdb790dad06dc6e5ece4a94da4c847fc..c42c53e7e368eaa83254a088d7d451e9cb770703 100644 (file)
@@ -122,6 +122,17 @@ class HttpRequest extends BaseFrameworkSystem implements Requestable {
                return $value;
        }
 
+       /**
+        * Setter for request elements
+        *
+        * @param       $element        Request element to se
+        * @param       $value          Value to set
+        * @return      void
+        */
+       public function setRequestElement ($element, $value) {
+               $this->requestData[$element] = $value;
+       }
+
        /**
         * Wrapper method for array_key() function for the request data array
         *
diff --git a/inc/classes/main/rng/.htaccess b/inc/classes/main/rng/.htaccess
new file mode 100644 (file)
index 0000000..3a42882
--- /dev/null
@@ -0,0 +1 @@
+Deny from all
diff --git a/inc/classes/main/rng/class_RandomNumberGenerator.php b/inc/classes/main/rng/class_RandomNumberGenerator.php
new file mode 100644 (file)
index 0000000..5856b9e
--- /dev/null
@@ -0,0 +1,140 @@
+<?php
+/**
+ * A standard random number generator
+ *
+ * @author             Roland Haeder <webmaster@ship-simu.org>
+ * @version            0.3.0
+ * @copyright  Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license            GNU GPL 3.0 or any newer version
+ * @link               http://www.mxchange.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+class RandomNumberGenerator extends BaseFrameworkSystem {
+       /**
+        * Prime number for better pseudo random numbers
+        */
+       private $prime = 0;
+
+       /**
+        * Add this calculated number to the rng
+        */
+       private $extraNumber = 0;
+
+       /**
+        * Extra salt for secured hashing
+        */
+       private $extraSalt = "";
+
+       /**
+        * Maximum length for salt
+        */
+       private $saltLength = 0;
+
+       /**
+        * Private constructor
+        *
+        * @param       $className      Name of this class
+        * @return      void
+        */
+       protected function __construct ($className = __CLASS__) {
+               // Call parent constructor
+               parent::__construct($className);
+
+               // Set part description
+               $this->setObjectDescription("Standard random number generator");
+
+               // Create unique ID number
+               $this->createUniqueID();
+
+               // Clean up a little
+               $this->removeNumberFormaters();
+               $this->removeSystemArray();
+       }
+
+       /**
+        * Creates an instance of this class
+        *
+        * @return      $rngInstance    An instance of this random number generator
+        */
+       public final static function createRandomNumberGenerator () {
+               // Get a new instance
+               $rngInstance = new RandomNumberGenerator();
+
+               // Initialize the RNG now
+               $rngInstance->initRng();
+
+               // Return the instance
+               return $rngInstance;
+       }
+
+       /**
+        * Initializes the random number generator
+        *
+        * @return      void
+        */
+       protected function initRng () {
+               // Get the prime number from config
+               $this->prime = $this->getConfigInstance()->readConfig('math_prime');
+
+               // Calculate the extra number which is always the same unless you give
+               // a better prime number
+               $this->extraNumber = ($this->prime * $this->prime / (pi() ^ 2));
+
+               // One-way data we need for "extra-salting" the random number
+               // @TODO Add site for stronger salt!
+               $this->extraSalt = sha1(getenv('SERVER_ADDR') . ":" . getenv('SERVER_SOFTWARE') . ":" . $this->getConfigInstance()->readConfig('date_key') . ":" . serialize($this->getDatabaseInstance()->getConnectionData()));
+
+               // Get config entry for max salt length
+               $this->saltLength = $this->getConfigInstance()->readConfig('salt_length');
+       }
+
+       /**
+        * Makes a pseudo-random string useable for salts
+        *
+        * @param       $length                 Length of the string, default: 128
+        * @return      $randomString   The pseudo-random string
+        */
+       public function makeRandomString ($length = -1) {
+               // Is the number <1, then fix it to default length
+               if ($length < 1) $length = $this->saltLength;
+
+               // Initialize the string
+               $randomString = "";
+
+               // And generate it
+               for ($idx = 0; $idx < $length; $idx++) {
+                       // Add a random character and add it to our string
+                       $randomString .= chr($this->randomNumnber(0, 255));
+               }
+
+               // Return the random string mixed up
+               return str_shuffle($randomString);
+       }
+
+       /**
+        * Generate a pseudo-random integer number in a given range
+        *
+        * @param       $min    Min value to generate
+        * @param       $max    Max value to generate
+        * @return      $num    Pseudo-random number
+        */
+       public function randomNumnber ($min, $max) {
+               // @TODO I had a better random number generator here
+               return mt_rand($min, $max);
+       }
+}
+
+// [EOF]
+?>
index 74196bc628b37dc82d5e2e1245f6b033a582c073..4e81d30de06c0b6fe7905cb154c538db62f0616e 100644 (file)
@@ -86,6 +86,15 @@ class DatabaseConnection extends BaseMiddleware implements DatabaseConnector, Li
                $this->connectData['host']  = (string) $host;
        }
 
+       /**
+        * Getter for connection data
+        *
+        * @return      $connectData    Connection data stored with this clas
+        */
+       public final function getConnectionData () {
+               return $this->connectData;
+       }
+
        /**
         * Save a whole object or parts of it to the database or local file
         *
index 33b04d8ca59cf36ea533f840fa8b1612db9946fa..879c84d678a8313df0e4cab9138f3efdcea9495e 100644 (file)
@@ -177,5 +177,20 @@ $cfg->setConfigEntry('password_validator', "PasswordValidatorFilter");
 // CFG: RULES-ACCEPTED-FILTER
 $cfg->setConfigEntry('rules_accepted_filter', "RulesAcceptedFilter");
 
+// CFG: CRYPTO-HELPER
+$cfg->setConfigEntry('crypto_heler', "CryptoHelper");
+
+// CFG: RNG-CLASS
+$cfg->setConfigEntry('rng_class', "RandomNumberGenerator");
+
+// CFG: MATH-PRIME
+$cfg->setConfigEntry('math_prime', 591623);
+
+// CFG: DATE-KEY
+$cfg->setConfigEntry('date_key', date("d-m-Y (l-F-T)", time()));
+
+// CFG: SALT-LENGTH
+$cfg->setConfigEntry('salt_length', 128);
+
 // [EOF]
 ?>