Board index   FAQ   Search  
Register  Login
Board index php forum :: Database mySQL & php coding

Intermittant Data Retrieval

Codes here !

Moderators: macek, egami, gesf

Intermittant Data Retrieval

Postby SeanFilner » Mon May 14, 2012 6:28 am

Hello all,

I am working on a project that utilizes mcrypt (serpent) and mySQL amongst other things.

I am storing an encryption key and initialization vector in a mySQL database. Each time the page loads the last key and iv are retrieved from the database and then a new key and initialization vector are generated from random alphanumeric characters and the database is updated. Sometimes it works and other times it doesn't.

The data that is being encrypted is a password (string) that is coded in base64, that string is then made sage to be passed into a URL and retrieved via get. The username is also being passed to the url. Once the next page is opened the encrypted/base64_encoded string is checked to replace any URL unsafe characters and base64_decoded. It uses the username to find the corresponding key & initialization vector. It is then decrypted with mcrypt (serpent) and the escape character is stripped off. The decrypted password is then hashed with sha512 and compared to a sha512 string that was previously stored.

I have concluded that the strings are being stored correctly however sometimes, approximately 50% of the time, there is a problem retrieving the key and iv from the database and using them to decrypt the password which is then hashed. When I compare the strings they are not evaluating true as they should. I have noticed that it happens less often when I take my time and wait >10 seconds before loading the next page.

I have manually defined static keys and ivs in the php code which will prevent this problem.

Does anybody have any solutions?

Thank You

Sean
SeanFilner
New php-forum User
New php-forum User
 
Posts: 2
Joined: Mon May 14, 2012 6:11 am

Re: Intermittant Data Retrieval

Postby Nullsig » Mon May 14, 2012 6:47 am

Can you show the code you are using?
User avatar
Nullsig
php-forum Fan User
php-forum Fan User
 
Posts: 981
Joined: Thu Feb 17, 2011 6:52 am
Location: Racine, WI

Re: Intermittant Data Retrieval

Postby SeanFilner » Mon May 14, 2012 7:03 am

Here is an assortment of the code that I am using. I have been playing with much of it to try and make it work so it might be a bit messy here and there.

Code: Select all
 // Make a base64_encoded string safe to put in a URL
            function UrlSafe_encode($string) {
                $data = base64_encode($string);
                $data = str_replace(array('+','/','='),array('-','_','.'),$data);
                return $data;
            }
// Decode a string that was made safe to put in a URL
            function UrlSafe_decode($string) {
                $data = str_replace(array('-','_','.'),array('+','/','='),$string);
                $mod4 = strlen($data) % 4;
                if ($mod4) {
                    $data .= substr('====', $mod4);
                }
                return base64_decode($data);
            }

// the token is used to prevent masquerading
function GenerateToken($username, $password, $timestamp) {
                $combined_string = $username . $password . $timstamp;
                return hash('sha256', $combined_string);
        }

        // check credentials, usually at page load.
        function VerifyCredentials($username, $password, $submitted_token) {
            require("config.inc.php");
            // set the authentication variable to false for default
            $proper_username = false;
            $proper_password = false;
            $proper_punch_age = false;
            $proper_token = false;
            $connect = mysql_connect($mysqlserver,$mysqluser,$mysqlpassword) or die("can't connect to mysql database");
            mysql_select_db($mysqldatabase, $connect);
            $user_table = $prefix . "users";
            // Use the above functions to decode and decrypt the username and password
            //$username = DecodeString($encrypted_username);
            //$password = DecodeString($encrypted_password);
            $result = mysql_query("SELECT * FROM $user_table WHERE username='$username'");
            while($row = mysql_fetch_array($result))
            {
                // retrieve the username from the database
                $checking_user = $row['username'];
                // does the username submitted match the username from the database
                //$compare = strcmp($checking_user, $username);
                if ($checking_user == $username) {
                        $proper_username = true;
                    }
                // retrieve the hashed password from the database
                $hash_password = $row['hashpass'];
                // hash the password from the user
                $checking_password = hash('sha512', $password);
                // does the hashed password from the submission match the hashed password from the database
                if ($checking_password == $hash_password) {
                        $proper_password = true;
                    }
               
                // retrieve the last timestamp (token punch)
                $last_timestamp = $row['tokenpunch'];
                // make sure the token is not more than X min old.
                $current_time = time();
                $token_punch_difference = $current_time - $last_timestamp;
                // Retrieve the user's expiration time in seconds
                $users_expiration = $row['expiration'];
                // make sure the last punch is no older than the user's expiration preference
                if ($token_punch_difference < $users_expiration) {
                        $proper_punch_age = true;
                    }
                // Here we are going to generate a token using the username, the password and the tokenpunch from the database.
                // We will then compare that to the token that was submitted via GET.
                // This will make sure the submitted token was not altered (is genuine).
                    //generate a token using the tokenpunch from the database.
                $database_token = GenerateToken($username, $password, $last_timestamp);
                    //make sure the tokens are the same.
                if ($submitted_token == $database_token) {
                        $proper_token = true;
                    }
               
                // if the usernames, passwords, tokens and expirations all validated, update the token punch and return true
                if (($proper_username == true) && ($proper_password == true) && ($proper_punch_age == true) && ($proper_token == true)) {
                        UpdateTokenPunch($username);
                        return true;
                    }
                // if they don't match, return false
                else {
                        return false;
                    }
           
            }
            mysql_close($connect);
        }

// generate a randome string
    function RandomString($length) {
        $seeds = "012345679abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        // Seed generator
        list($usec, $sec) = explode(' ', microtime());
        $seed = (float) $sec + ((float) $usec * 100000);
        mt_srand($seed);
        // Generate
        $str = "";
        $seeds_count = strlen($seeds);
        for ($i = 0; $length > $i; $i++)
        {
            $str .= $seeds{mt_rand(0, $seeds_count - 1)};
        }
        return $str;
    }

// return page expiration in minutes
        function PageExpiration($username) {
            require("config.inc.php");
            $connect = mysql_connect($mysqlserver,$mysqluser,$mysqlpassword) or die("can't connect to mysql database");
            mysql_select_db($mysqldatabase, $connect);
            $user_table = $prefix . "users";
            $result = mysql_query("SELECT * FROM $user_table WHERE username='$username'");
            while($row = mysql_fetch_array($result))
            {
                $expiration = $row['expiration'];
                // expiration is in seconds, change it to minutes.
                $expiration = $expiration / 60;
            }
            mysql_close($connect);
            return $expiration;
        }

//Encrypt data using serpent - not safe for blob database
            function SerpentEncryptData ($unencrypted_data, $key, $iv) {
                $encrypted_data = mcrypt_encrypt(MCRYPT_SERPENT, $key, $unencrypted_data, MCRYPT_MODE_CBC, $iv);
                return $encrypted_data;
            }
       
        // Decrypt data using mcrypt serpent in cbc mode and return it stripped of escape characters.
        function SerpentDecrypt ($encrypted_data, $key, $iv) {
                $decrypted_data = mcrypt_decrypt(MCRYPT_SERPENT, $key, $encrypted_data, MCRYPT_MODE_CBC, $iv);
                $decrypted_data = rtrim($decrypted_data, "\0");
                return $decrypted_data;
            }

 // Update password encryption key and iv
        function UpdatePasswordEncryption($username) {
            require("config.inc.php");
            $connect = mysql_connect($mysqlserver,$mysqluser,$mysqlpassword) or die("can't connect to mysql database");
            mysql_select_db($mysqldatabase, $connect);
            $random_number = 33242; //mt_rand();
            echo "<p> mt rand: $random_number <p>";
            $random_hash = hash('sha256', $random_number);
            $new_random_key = substr($random_hash, 2, 32);
            //$new_random_key = mysql_real_escape_string($new_random_key);
            //$new_random_key = RandomString(32);
            //$new_random_iv =  "1234567890123456"; // mt_rand(RandomGen(16);
            $new_random_iv = substr($random_hash, 34, 16);
            //$new_random_iv = mysql_real_escape_string($new_random_iv);
            //require("config.inc.php");
            //$connect = mysql_connect($mysqlserver,$mysqluser,$mysqlpassword) or die("can't connect to mysql database");
            //mysql_select_db($mysqldatabase, $connect);
            $user_table = $prefix . "users";
           
            mysql_query("UPDATE $user_table SET loadkey = '$new_random_key' WHERE username = '$username'");
            mysql_query("UPDATE $user_table SET loadiv = '$new_random_iv' WHERE username = '$username'");
            mysql_close($connect);
            //return $timestamp;
            }
           
            // retrieve a user's password encryption key
            function GetPasswordEncryptionKey($username) {
                require("config.inc.php");
                $connect = mysql_connect($mysqlserver,$mysqluser,$mysqlpassword) or die("can't connect to mysql database");
                mysql_select_db($mysqldatabase, $connect);
                $user_table = $prefix . "users";
                $result = mysql_query("SELECT * FROM $user_table WHERE username='$username'");
                while($row = mysql_fetch_array($result))
                {
                    $loadkey = $row['loadkey'];
                }
                mysql_close($connect);
                return $loadkey;
            }
           
            // retrieve a user's password encryption iv
            function GetPasswordEncryptionIv($username) {
                require("config.inc.php");
                $connect = mysql_connect($mysqlserver,$mysqluser,$mysqlpassword) or die("can't connect to mysql database");
                mysql_select_db($mysqldatabase, $connect);
                $user_table = $prefix . "users";
                $result = mysql_query("SELECT * FROM $user_table WHERE username='$username'");
                while($row = mysql_fetch_array($result))
                {
                    $loadiv = $row['loadiv'];                   
                    //$length = strlen($loadiv);
                    //echo "<p> Iv length: $length <p>";
                    //echo "<p> from GetPasswordEncryptionIv: $loadiv <p>";
                }
                mysql_close($connect);
                return $loadiv;
            }


SeanFilner
New php-forum User
New php-forum User
 
Posts: 2
Joined: Mon May 14, 2012 6:11 am


Return to mySQL & php coding

Who is online

Users browsing this forum: Bing [Bot], randdnar and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.