-
-
Save abesto/1122496 to your computer and use it in GitHub Desktop.
How to use bcrypt in PHP to safely store passwords (PHP 5.3+ only)
This file contains hidden or 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
<?php | |
// secure hashing of passwords using bcrypt, needs PHP 5.3+ | |
// see http://codahale.com/how-to-safely-store-a-password/ | |
// salt for bcrypt needs to be 22 base64 characters (but just [./0-9A-Za-z]), see http://php.net/crypt | |
// 2a is the bcrypt algorithm selector, see http://php.net/crypt | |
// 12 is the workload factor (around 300ms on a Core i7 machine), see http://php.net/crypt | |
function bcrypt($message, $salt, $cost=12) | |
{ | |
if (preg_match('~[./0-9A-Za-z]{22}~', $salt) === 0) throw new RuntimeException('bcrypt expects a salt of 22 digits of the alphabet [./0-9A-Za-z]'); | |
if ($cost < 4 || $cost > 31) throw new RuntimeException('bcrypt expects cost parameter between 04 and 31'); | |
return substr(crypt($message, '$2a$'.sprintf('%02d', $cost).'$'.$salt), 29); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment