Created
March 28, 2013 20:06
-
-
Save luads/5266358 to your computer and use it in GitHub Desktop.
Authenticate an external app through a Symfony2 + FOSUserBundle database
This file contains 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 | |
class PasswordService | |
{ | |
public function __construct($algorithm = 'sha512', $encodeHashAsBase64 = true, $iterations = 5000) | |
{ | |
$this->algorithm = $algorithm; | |
$this->encodeHashAsBase64 = $encodeHashAsBase64; | |
$this->iterations = $iterations; | |
} | |
public function encodePassword($raw, $salt) | |
{ | |
$salted = $this->mergePasswordAndSalt($raw, $salt); | |
$digest = hash($this->algorithm, $salted, true); | |
for ($i = 1; $i < $this->iterations; $i++) { | |
$digest = hash($this->algorithm, $digest.$salted, true); | |
} | |
return $this->encodeHashAsBase64 ? base64_encode($digest) : bin2hex($digest); | |
} | |
public function isPasswordValid($encoded, $raw, $salt) | |
{ | |
return $this->comparePasswords($encoded, $this->encodePassword($raw, $salt)); | |
} | |
protected function mergePasswordAndSalt($password, $salt) | |
{ | |
if (empty($salt)) { | |
return $password; | |
} | |
if (false !== strrpos($salt, '{') || false !== strrpos($salt, '}')) { | |
throw new \InvalidArgumentException('Cannot use { or } in salt.'); | |
} | |
return $password.'{'.$salt.'}'; | |
} | |
protected function comparePasswords($password1, $password2) | |
{ | |
return self::equals($password1, $password2); | |
} | |
private static function equals($knownString, $userInput) | |
{ | |
$knownString .= chr(0); | |
$userInput .= chr(0); | |
$knownLen = strlen($knownString); | |
$userLen = strlen($userInput); | |
$result = $knownLen - $userLen; | |
for ($i = 0; $i < $userLen; $i++) { | |
$result |= (ord($knownString[$i % $knownLen]) ^ ord($userInput[$i])); | |
} | |
return 0 === $result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment