Skip to content

Instantly share code, notes, and snippets.

@thers
Created July 22, 2013 07:11
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 thers/6051864 to your computer and use it in GitHub Desktop.
Save thers/6051864 to your computer and use it in GitHub Desktop.
<?php
class Hash {
/**
* Hash a password using the Bcrypt hashing scheme.
*
* <code>
* // Create a Bcrypt hash of a value
* $hash = Hash::make('secret');
*
* // Use a specified number of iterations when creating the hash
* $hash = Hash::make('secret', 12);
* </code>
*
* @param string $value
* @param int $rounds
* @return string
*/
public static function make($value, $rounds = 8)
{
$work = str_pad($rounds, 2, '0', STR_PAD_LEFT);
// Bcrypt expects the salt to be 22 base64 encoded characters including
// dots and slashes. We will get rid of the plus signs included in the
// base64 data and replace them with dots.
if (function_exists('openssl_random_pseudo_bytes'))
{
$salt = openssl_random_pseudo_bytes(16);
}
else
{
$salt = static::random(40);
}
$salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);
return crypt($value, '$2a$'.$work.'$'.$salt);
}
/**
* Determine if an unhashed value matches a Bcrypt hash.
*
* @param string $value
* @param string $hash
* @return bool
*/
public static function check($value, $hash)
{
return crypt($value, $hash) === $hash;
}
/**
* Generate a random alpha or alpha-numeric string.
*
* <code>
* // Generate a 40 character random alpha-numeric string
* echo Str::random(40);
* <code>
*
* @param int $length
* @return string
*/
public static function random($length)
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment