Skip to content

Commit 01b7268

Browse files
enygmaalexweissman
authored andcommitted
Refacotring on the Password class to use hash_equals (timing attack safe) and making the default cost a constant
1 parent 9e5330a commit 01b7268

1 file changed

Lines changed: 8 additions & 4 deletions

File tree

app/sprinkles/account/src/Util/Password.php

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
*/
1515
class Password
1616
{
17+
const DEFAULT_COST = 12;
18+
1719
/**
1820
* Returns the hashing type for a specified password hash.
1921
*
@@ -26,7 +28,7 @@ public static function getHashType($password)
2628
// If the password in the db is 65 characters long, we have an sha1-hashed password.
2729
if (strlen($password) == 65) {
2830
return 'sha1';
29-
} elseif (substr($password, 0, 7) == '$2y$12$') {
31+
} elseif (substr($password, 0, 7) == '$2y$'.self::$_DEFAULT_COST.'$') {
3032
return 'legacy';
3133
}
3234

@@ -64,7 +66,7 @@ public static function verify($password, $hash)
6466
// Legacy UserCake passwords
6567
$salt = substr($hash, 0, 25); // Extract the salt from the hash
6668
$hashInput = $salt . sha1($salt . $password);
67-
if ($hashInput == $hash) {
69+
if (hash_equals($hashInput, $hash) === true) {
6870
return true;
6971
}
7072

@@ -73,8 +75,10 @@ public static function verify($password, $hash)
7375
} elseif (static::getHashType($hash) == 'legacy') {
7476
// Homegrown implementation (assuming that current install has been using a cost parameter of 12)
7577
// Used for manual implementation of bcrypt.
76-
$cost = '12';
77-
if (substr($hash, 0, 60) == crypt($password, '$2y$' . $cost . '$' . substr($hash, 60))) {
78+
$extract = substr($hash, 0, 60);
79+
$compare = crypt($password, '$2y$' . self::$DEFAULT_COST . '$' . substr($hash, 60));
80+
81+
if (hash_equals($extract, $compare) === true) {
7882
return true;
7983
}
8084

0 commit comments

Comments
 (0)