Rehash MD5 password in Drupal 8

Posted on 17/09/2019

Below is a simple code snippet that allows you to convert a password hashed using MD5 into the format that can be used by Drupal 8. This can be useful if you are creating users programmatically and need to re-create their password from an MD5 source.

  1.   /** @var \Drupal\Core\Password\PhpassHashedPassword $password_service */
  2.   $password_service = \Drupal::service('password');
  3.   $password = md5('testmetestme');
  4.   // U will indicate that the password needs rehashing.
  5.   // Method is the same as in Drupal 7. See user_update_7000() for more info.
  6.   $hashed_password = 'U' . $password_service->hash($password);