Skip to content

Instantly share code, notes, and snippets.

@mbutler
Created February 22, 2012 22:41
Show Gist options
  • Save mbutler/1888057 to your computer and use it in GitHub Desktop.
Save mbutler/1888057 to your computer and use it in GitHub Desktop.
A password hashing function. Covering the standard bases. Slow paced, long hashes, individual salt. Avoiding brute force, collisions and rainbowtables.
<?php
//http://endrerudsorensen.com/~f/slowsauce/
class slowsauce
{
private static $algo = "ripemd256";
private static $rounds = 10000;
public static function salt()
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$salt = '';
for( $i=0 ; $i < 10 ; $i++ )
$salt .= substr($chars, mt_rand(0, 62), 1);
return substr( sha1( $salt ) , 2 , 20 );
}
public static function hash($text, $salt=null)
{
if($salt === null)
$salt = self::salt();
$hash = $text . $salt;
for( $i=0 ; $i < self::$rounds ; $i++)
$hash = hash( self::$algo, $hash );
return $salt .'$'. $hash;
}
public static function compare($hash, $text)
{
$slicedHash = explode('$', $hash );
$saltLen = strlen($slicedHash[0]);
if(!is_integer($saltLen))
return false;
$salt = substr($hash, 0, $saltLen );
$textHash = self::hash($text, $salt);
return $hash === $textHash;
}
public static function debug($return=false)
{
$hash_algos = hash_algos(); // Supported algorithms
foreach($hash_algos as $algo)
if($algo == self::$algo)
$debug['algo'] = "[Works/Supported]";
if(!isset($debug))
$debug['algo'] = "[ERROR!]";
$testPassword = 'My@Password^';
$hash = self::hash($testPassword);
if( self::compare($hash, $testPassword) )
$debug['hash_compare'] = "[Works/Supported]";
else
$debug['hash_compare'] = "[ERROR!]";
$debug['test_hash'] = $hash;
if($return === false)
foreach($debug as $name => $val)
echo "$name: $val <br />\n";
else
return $debug;
}
}
// Test class
slowsauce::debug();
// $hash = slowsauce::hash($plaintextpassword); // Create a hash
// $boolean = slowsauce::compare($hash, $password); // Returns true if hash matches the password. If not, false is returned
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment