-
-
Save blackknight36/c7348778a0e5bdc4853df94cca09337c to your computer and use it in GitHub Desktop.
SSHA password hashing. this format is used by OpenLDAP to store passwords
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
function make_salt($salt_size=32) { | |
//list of possible characters from which to cerate the salt | |
$sea = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | |
//how many possible characters are there | |
$sea_size = strlen($sea); | |
$salt = ""; | |
for ($i = 0; $i < $salt_size; $i ++) { | |
//randomly select a character from the sea | |
$salt .= substr($sea, rand(0, $sea_size - 1), 1); | |
} | |
return $salt; | |
} | |
function hashPassword($password, $salt) { | |
//salt must be 32 characters in length | |
if (strlen($salt) !== 32) throw New Exception("salt must be 32 characters long"); | |
//hash the salted password | |
$sha_hashed = sha1($password.$salt); | |
//pack the hash into a binary string | |
$packed = pack("H*",$sha_hashed); | |
//combine the binary hash with the salt and encode into base 64 | |
$encoded = base64_encode($packed.$salt); | |
//add the hash type identifier to the start of the string | |
$ssha_hash = "{SSHA}".$encoded; | |
return $ssha_hash; | |
} | |
function comparePassword($password, $ssha_hash) { | |
//slice the hash type identifier ({SSHA}) off the start of the string | |
$encoded_string = substr($ssha_hash, 6); | |
//decode from base 64, so we can find the salt | |
$decoded = base64_decode($encoded_string); | |
//get the salt | |
$salt = substr($decoded, -32); | |
//hash the password we've been given, and compare it with the other hashed password | |
return hashPassword($password, $salt) == $ssha_hash; | |
} | |
function test() { | |
//salt must be 32 characters in length | |
$salt = "mcqaIyeGCGBQVmDxFP9UNc9czIVAy31K"; | |
$password = "foobar123"; | |
//create a hashed password | |
$ssha_hash = hashPassword($password, $salt); | |
//make sure comparePassword returns false when the password doesn't match the hash | |
$wrong_password = "lalala"; | |
if (comparePassword($wrong_password, $ssha_hash) !== false) throw New Exception("should have failed - we gave the wrong password"); | |
//make sure comparePassword returns true when the password matches the hash | |
$right_password = "foobar123"; | |
if (comparePassword($right_password, $ssha_hash) !== true) throw New Exception("should have succeeded - we gave the right password"); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment