如果您有一个包含用户及其密码的现有代码库,您如何更改密码编码器并更新用户密码?
换句话说,假设所有用户密码都在 MD5 中,并且您想转换到 PBKDF2。常见的策略是在用户下次登录时简单地重新散列密码。
但是,我不确定如何在 Symfony 中执行此操作。会在登录控制器中完成吗?或者有没有办法在 EncoderInterface 对象中做到这一点?
如果您有一个包含用户及其密码的现有代码库,您如何更改密码编码器并更新用户密码?
换句话说,假设所有用户密码都在 MD5 中,并且您想转换到 PBKDF2。常见的策略是在用户下次登录时简单地重新散列密码。
但是,我不确定如何在 Symfony 中执行此操作。会在登录控制器中完成吗?或者有没有办法在 EncoderInterface 对象中做到这一点?
Check out this blog... seems like this is what you're looking for...
How to change the way Symfony2 encodes passwords
You need to extend MessageDigestPasswordEncoder class, overwrite its methods and copy that class to the Security folder in your bundle (create one if not exist) Check out the following example of how to extend MessageDigestPasswordEncoder
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder as BaseMessageDigestPasswordEncoder;
class MessageDigestPasswordEncoder extends BaseMessageDigestPasswordEncoder
{
private $algorithm;
private $encodeHashAsBase64;
public function __construct($algorithm = 'sha512', $encodeHashAsBase64 = true, $iterations = 5000)
{
$this->algorithm = $algorithm;
$this->encodeHashAsBase64 = $encodeHashAsBase64;
$this->iterations = $iterations;
}
protected function mergePasswordAndSalt($password, $salt)
{
if (empty($salt)) {
return $password;
}
return $salt.$password; // or do whatever you need with the password and salt
}
public function encodePassword($raw, $salt)
{
// this is the original code from the extended class, change it as needed
if (!in_array($this->algorithm, hash_algos(), true)) {
throw new \LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm));
}
$salted = $this->mergePasswordAndSalt($raw, $salt);
$digest = hash($this->algorithm, $salted, true);
// "stretch" hash
for ($i = 1; $i < $this->iterations; $i++) {
$digest = hash($this->algorithm, $digest.$salted, true);
}
return $this->encodeHashAsBase64 ? base64_encode($digest) : bin2hex($digest);
}
}
After you have your class ready update your config.yml
# app/config/config.yml
# ...
parameters:
security.encoder.digest.class: Ens\TestBundle\Security\MessageDigestPasswordEncoder