Skip to content

Instantly share code, notes, and snippets.

@gsdevme
Created August 8, 2012 11:14
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 gsdevme/3294324 to your computer and use it in GitHub Desktop.
Save gsdevme/3294324 to your computer and use it in GitHub Desktop.
Hashing Utilities
<?php
namespace Utilities;
class Hash
{
const PASSWORD_STRENGTHENING = 50000;
/**
* Allows for salt outside of this class
*
* @author Gavin Staniforth <@gsphpdev>
* @param String $string
* @param String $salt
* @return {hash: (128char), salt: (32char)}
*/
public static function hash($string, $salt=null)
{
if($salt === null){
// Convert from null, to an empty string
$salt = (string)$salt;
// create a 128 char random salt
for($i=0;$i<128;++$i){
// use the ascii character set to create a random char, http://www.asciitable.com/
$salt += chr(rand(33, 122));
}
// hash it up so ensure its 'always' 32 chars & A-Z0-9. so the field salt === varchar(32)
$salt = md5($salt);
}
$hash = $string;
for($i=0;$i<self::PASSWORD_STRENGTHENING;++$i){
$hash = hash('sha512', $hash . $salt);
}
return (object)array(
'hash' => $hash,
'salt' => $salt
);
}
/**
* Asserts a match
*
* @author Gavin Staniforth <@gsphpdev>
* @param String $string
* @param String $hash
* @param String $salt
* @return boolean
*/
public static function assert($string, $hash, $salt)
{
$currentHash = $string;
for($i=0;$i<self::PASSWORD_STRENGTHENING;++$i){
$currentHash = hash('sha512', $currentHash . $salt);
}
return (bool)($currentHash === $hash);
}
}
$x = Hash::hash('password');
echo '<h1>Hashed Dump</h1><pre>' . print_r($x, true) . '</pre>';
$b = Hash::assert('password', $x->hash, $x->salt);
echo '<h1>Assert Dump</h1>' . var_dump($b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment