Recently I came upon a problem where the passwords of the current user base are hashed in md5 and we had to migrate them to sha. Checking around the web how others have solved this didn’t help a lot. Asking your user to login to change the password or double encode the md5 one didn’t sound like clever solutions.

The main authentication process in symfony is happening in DaoAuthenticationProvider.

{% highlight php startinline=true %} if (!$this->encoderFactory->getEncoder($user)->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt())) { throw new BadCredentialsException(‘The presented password is invalid.’); } {% endhighlight %}

What I end up doing is to actually leave this as a final password check but prior to that authenticate the user once with the md5 and generate the sha with the given password. On the same I clear the legacy md5 field in order to know which users are actually updated and prevent the check of happening again in the future.

{% highlight php startinline=true %} if ("" !== ($legacyPassword = $user->getLegacyPassword())) { if ($legacyPassword === hash(‘md5’, $presentedPassword)) { $user->setPlainPassword($presentedPassword); $user->setLegacyPassword(null); $this->userManager->updateUser($user); } }

if (!$this->encoderFactory->getEncoder($user)->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt())) { throw new BadCredentialsException(‘The presented password is invalid.’); } {% endhighlight %}

Cheers