Skip to content

Instantly share code, notes, and snippets.

@richjava
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richjava/aa2be4ac004c325170d1 to your computer and use it in GitHub Desktop.
Save richjava/aa2be4ac004c325170d1 to your computer and use it in GitHub Desktop.
PHP Password hashing for PHP 5.5.0 and less
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP Password hashing for PHP 5.5.0 and less</title>
</head>
<body>
<h2>PHP Password encryption for PHP 5.5.0 and less</h2>
<p>For PHP versions greater than 5.5.0, there is an in-built hashing method (see <a href="http://php.net/manual/en/function.password-hash.php">password_hash</a>), but you could still use this method if you wish.</p>
<?php
//******** For registration
//Let's pretend $password is the password that the user has inputted in the registration form
$password = 'myPassword';
// Create a random salt
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)),'+', '.');
echo "------Registering-------<br/>password: $password<br/>Salt: $salt<br/>";
// Hash the password with the salt. This hash will be saved in the db.
$hash = crypt($password, $salt);
//******** For login
//Let's pretend:
//1. $password is the password that the user has inputted in the login form, and
//2. We have retrieved the password from the db (where the username
//matches the inputted username) and stored it in a variable called $hash
displayLogin($password, $hash);
//Let's try again with an incorrect password
$incorrectPassword = "myIncorrectPassword";
displayLogin($incorrectPassword, $hash);
/**
* Hashing the password with its hash as the salt returns the same hash.
*/
function logIn($password, $hash){
if (crypt($password, $hash) === $hash) {
return true;
}
return false;
}
/**
* This is just used for display purposes.
* @param type $password
* @param type $hash
*/
function displayLogin($password, $hash){
echo "<br/>------Logging in-------<br/>Password that user used to login: $password<br/>Hash for db: "
. "$hash<br/>";
if(logIn($password, $hash)){
echo 'Password is valid!<br/>';
}else{
echo 'Password is not valid!<br/>';
}
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment