WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
Internet Security Software
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
פרייסז - הכח לקנות עובר לידיים שלך
Texas Holdem Poker Evangelists

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Generating and Matching Secure and Strong Password Hash
Categories : PHP, PHP Classes, Cryptography, Security Click here to Update Your Picture
MA Razzaque Rupom
Date : Jun 03rd 2006
Grade : 5 of 5 (graded 2 times)
Viewed : 10703
File : 4412.zip
Images : No Images for this code example.
Search : More code by MA Razzaque Rupom
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
 

This technique of generating password hash (or password digest) generates strong hash of plain
text password. And for authentication, it matches a generated hash with a plain password.

Modern computers can generate both md5() and sha1() very quickly, thousands per seconds. Thus
generating hashes and matching with existing hashes (for hacking) is easy. The present technique
implements a kind of hashing that makes strong salt, decodes that and makes hash with that decoded
salt and the given password. It gives a variable length strong hash that makes attackers' job tough.


Description:
This technique -
1. Creates strong salt of given length
2. Makes that salt more strong by decoding it to binary data
3. Creates hash appending that salt to the output of secure hash algorithm - 1
(sha1)generated hash. Parameter of SHA1 in this case is (decoded salt + plainpassword)
4. In matching a password with a stored hash,

(i) The salt is extracted from given/stored hash and decoded first
(ii) Then sha1() is implemented on that salt + plain password
(iii) Then this hash is compared with the sha1() generated-hash portion of given/stored hash


Strengths :
1. If no parameter is given, initSalt() generates random salt that eventually generates random password hash for the same plain password.
2. When password characters are only plaintext, attackers' job is easy. Use of base64_decode()
helps this technique generate more strong password since the hash contains binary data.
3. Changing the length of salt (saltLength), you can generate password of variable lengths(upto 70 characters).
This strengthens the password and makes attackers' job tough.



SecurePassword.class.php
<?php
/**
* Class : Secure Password
*
* @PHPVER  :  5.0
* @author  :  MA Razzaque Rupom <rupom_315@yahoo.com>, <rupom.bd@gmail.com>
*             Moderator, phpResource (http://groups.yahoo.com/group/phpresource/)
*             URL: http://www.rupom.info 
*       
* @version :  1.0
* Date     :  06/03/2006
* Purpose  :  Generating and Matching Secure and Strong Password Hash
*/

class SecurePassword
{     
     private
$salt;
     private
$saltLength = 20; //+ve and <=40
     
     /**
     * Initializes Salt
     * @param Salt
     * @return none
     */
   
function initSalt($salt = null)
   {
     
$this->salt = !empty($salt) ? $this->getSalt($salt) : $this->randomSalt();     
   }
   
   
/**
     * Generates password hash
     * @param plain password text
     * @return secure password hash
     */
   
function generatePasswordHash($passwordText)
   {
         
//data is not only plain, may be binary also
         
$decodedSalt = base64_decode($this->salt);
     
     
//password from salt and sha1(of decoded salt and plain password)     
     
$password    = $decodedSalt.sha1($decodedSalt.$passwordText);
     
      return
$password;
   }
   
   
/**
   * Creates Random Salt
   * @param none
   * @return Random Salt
   */
   
function randomSalt()
   {
     
mt_srand($this->makeSeed()); //since PHP 4.2.0, seed is no longer needed
     
$randVal = mt_rand(); //random value
     
return $this->getSalt($randVal);
   }

   
/**
   * Gets Salt
   * @param string to be formatted-salt
   * @return String Salt
   */   
   
function getSalt($salt)
   {
     
$saltStr = sha1($salt); //use of secure hash algorithm-1       
     
$saltStr = substr($saltStr,0,$this->saltLength); //salt according to saltLength
     
return $saltStr;
     
   }
   
/**
   * Seed with microseconds
   * @param none
   * @return float
   */
   
function makeSeed()
   {
       list(
$usec, $sec) = explode(' ', microtime());
       return (float)
$sec + ((float) $usec * 100000);
   }
   
   
/**
   * Manipulates hash and matches it with password
   * @param plain password and digested password(hash)
   * @return boolean true in success, false otherwise
   */
   
function matchPassword($plainPassword, $passwordDigest)
   {           
     
$tempStr       = str_repeat('1',$this->saltLength);
     
     
//No. of salt chars in the digest
     
$saltStrLength = strlen(base64_decode($tempStr));     
     
     
//Retrieving salt string
     
$saltStr       = base64_encode(substr($passwordDigest, 0, $saltStrLength));
     
     
//Extracting sha1() digested string
     
$hashPrev      = substr($passwordDigest, $saltStrLength);           
     
     
//Creating sha1() digest by the $plainPassword
     
$hashNow       = sha1(base64_decode($saltStr).$plainPassword);     
           
     
// Comparing the given one and the newly created one
     
if(!strcmp($hashPrev, $hashNow))
      {
         return
true; //Password is correct
     
}
     
      return
false; //Password is incorrect
   
}
   
   
/**
   * Formats output (for debugging purpose)
   * @param debug data
   * @return none
   */
   
function dBug($dump)
   {
      echo
"<PRE>";   
     
print_r($dump);
      echo
"</PRE>";   
   }
   
}
//EO Class

?>



Usage Example
<?php
/**
* Class : Secure Password
*
* @PHPVER  :  5.0
* @author  :  MA Razzaque Rupom <rupom_315@yahoo.com>, <rupom.bd@gmail.com>
*             Moderator, phpResource (http://groups.yahoo.com/group/phpresource/)
*             URL: http://www.rupom.info 
*       
* @version :  1.0
* Date     :  06/03/2006
* Purpose  :  Generating and Matching Secure and Strong Password Hash
*/

require_once "SecurePassword.class.php";

$obj = new SecurePassword();
$obj->initSalt();
$password = 'abcd'; //password
$hash = $obj->generatePasswordHash($password);  //hash created

//Matching results true if this $hash is for this $password
if($obj->matchPassword($password, $hash)) //match password by the hash
{
   echo
"<br>YES, Matched";
}
else
{
   echo
"<br>No, Wrong Password";
}

//Try with wrong password
$wrongPassword = 'asdf';

if(
$obj->matchPassword($wrongPassword, $hash)) //match password by the hash
{
   echo
"<br>YES, Matched";
}
else
{
   echo
"<br>No, Wrong Password";
}


//Hash from DB

//DB Connection
mysql_connect("dbhost","dbuser","dbpass");
mysql_select_db("db");

$sourceTable = 'yourtable';

$q = "SELECT password FROM $sourceTable where name='rupom'";               
$res = mysql_query($q);
     
if(
mysql_num_rows($res))
{
   while(
$row = mysql_fetch_array($res))
   {             
         
$hash = $row['password'];         
         break;             
   }
}

if(
$obj->matchPassword($password, $hash)) //match password by the hash
{
   echo
"<br>YES, Matched";
}
else
{
   echo
"<br>No, Wrong Password";
}
?>



A damaged image generator (class) for validating text. CAPTCHA - Completely Automated Public Turing test to tell Computers and Humans Apart
Categories : PHP, PHP Classes, Security, GD image library, Security
Function to generate readable/remeberable random password
Categories : PHP, Security, Security
Password Creator: This PHP code exmaple shows how to use bitwise operations on a single variable and using it as a flagged variable. The class generates passwords of a given length using specified characters and the flags.
Categories : PHP, PHP Classes, Algorithms, Security
Encoding data using PGP via PHP's proc_* functions
Categories : Cryptography, Security, Email, PHP, PGP
Scramble Eggs - php class to scramble/encode
Categories : PHP, PHP Classes, Security, Encryption
Forms protected from XSS attacks (FOPAXSS)
Categories : PHP, PHP Classes, Form Processing, Security
Use of bitmasks to represent permissions
Categories : PHP, Authentication, Bitwise Operators, Security, PHP Classes
Scan Apache access log files and report possible worms attack
Categories : PHP, PHP Classes, Security, Apache, Log Files
Distribute PHP Software Protected by a License Key.
Categories : PHP, Cryptography, Security, Software
Antispoof - a class to help prevent people hi-jacking and misusing parts of a website
Categories : PHP, PHP Classes, Security
Sort the results from a SELECT query (any number of columns) into an array automatically.
Categories : PHP, PHP Classes, Arrays, Databases, MySQL
usercounter class
Categories : PHP, PHP Classes, Databases, MySQL, Environment Variables
POP3 Class
Categories : PHP Classes, PHP, Email
Generate image with random number (CAPTCHA)
Categories : PHP, GD image library, Graphics, Security
Search and Replace Text : Searches Files for Specified Text and Replaces It by a Given Text
Categories : PHP, PHP Classes, Search, Filesystem