Skip to content

Instantly share code, notes, and snippets.

@hqmatics
Created August 19, 2013 06:03
Show Gist options
  • Save hqmatics/6266104 to your computer and use it in GitHub Desktop.
Save hqmatics/6266104 to your computer and use it in GitHub Desktop.
PHP Password hashing
<?php
$username = 'Admin';
$password = 'gf45_gdf#4hg';
// A higher "cost" is more secure but consumes more processing power
$cost = 10;
// Create a random salt
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
// Prefix information about the hash so PHP knows how to verify it later.
// "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
$salt = sprintf("$2a$%02d$", $cost) . $salt;
// Value:
// $2a$10$eImiTXuWVxfM37uY4JANjQ==
// Hash the password with the salt
$hash = crypt($password, $salt);
// Value:
// $2a$10$eImiTXuWVxfM37uY4JANjOL.oTxqp7WylW7FCzx2Lc7VLmdJIddZq
// Verify
$username = 'Admin';
$password = 'gf45_gdf#4hg';
$sth = $dbh->prepare('
SELECT
hash
FROM users
WHERE
username = :username
LIMIT 1
';
$sth->bindParam(':username', $username);
$sth->execute();
$user = $sth->fetch(PDO::FETCH_OBJ);
// Hashing the password with its hash as the salt returns the same hash
if ( crypt($password, $user->hash) == $user->hash ) {
// Ok!
}
@afroald
Copy link

afroald commented Aug 19, 2013

Is het de bedoeling dat deze Gist openbaar is?

@hqmatics
Copy link
Author

hqmatics commented Sep 5, 2013

Oh.. ja, password is example :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment