Symfony2 - 为现有用户更改编码器

时间:2014-09-09 22:52:06

标签: php symfony login passwords password-hash

如果您拥有包含用户及其密码的现有代码库,那么如何更改密码编码器并让用户使用?密码更新?

换句话说,让我们说所有用户密码都在MD5中,并且您想要转换到PBKDF2。常见的策略是在用户下次登录时简单地重新哈希密码。

但是,我不确定如何在Symfony中执行此操作。它会在登录控制器中完成吗?或者有没有办法在EncoderInterface对象中执行此操作?

1 个答案:

答案 0 :(得分:3)

看看这个博客......看起来这就是你正在寻找的......

How to change the way Symfony2 encodes passwords

您需要扩展MessageDigestPasswordEncoder类,覆盖其方法并将该类复制到捆绑包中的Security文件夹(如果不存在,则创建一个) 查看以下有关如何扩展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);
    }
}

准备好课程后,请更新config.yml

# app/config/config.yml
# ...

parameters:
    security.encoder.digest.class: Ens\TestBundle\Security\MessageDigestPasswordEncoder