Skip to main content
Category:

In this article, I'll show you how to change hashing algorithm in drupal 8 by creating our custom "codimth_hashedpassword" module.

this tuto is an example, I used for migrating users passwords from non-drupal database to Drupal 8.

Create codimth_hashedpassword.info.yml file:

name: Codimth Hashed Password Alter
description: "create custom Hashed Password"
type: module
package: 'Codimth'
core: 8.x

Create codimth_hashedpassword.services.yml file:

I define a new service to process all the submitted passwords from users by adding a codimth_hashedpassword.services.yml file with the following:

services:
  codimth_hashedpassword:
    class: Drupal\codimth_hashedpassword\CodimthHashedPasswordService

Create src/CodimthHashedPasswordService.php file:

<?php

namespace Drupal\codimth_hashedpassword;

use Drupal\Component\Utility\Crypt;
use Drupal\Core\Password\PhpassHashedPassword;
use Drupal\Core\Password\PasswordInterface;

/**
 * Class CodimthHashedPasswordService
 * @package Drupal\codimth
 */
class CodimthHashedPasswordService extends PhpassHashedPassword implements PasswordInterface
{

  /**
   * @param string $password
   * @param string $hash
   * @return bool
   */
  public function check($password, $hash)
  {
    $computed_hash = md5($password);
    if ($computed_hash && Crypt::hashEquals($hash, $computed_hash)) {      
      return $computed_hash && Crypt::hashEquals($hash, $computed_hash);
    }
    return parent::check($password, $hash);
  }
}

I override the  Drupal/Core/Password/PhpassHashedPassword.php class and override the check() method to include my custom logic.

md5() function calculates the MD5 hash of a string.

When user logs in, the check() method is going to do the following:

  • hash password with md5() and compare it with the one stored during migration, if they are the same returns the result of 

    $computed_hash && Crypt::hashEquals($hash, $computed_hash)

  • If  users registered on drupal 8 site, it uses logic from PhpassHashedPassword class provided by Drupal core.(return parent::check($password, $hash);)

Next steps

  • Clear your Drupal 8 caches. To do this I use this Drush command: drush cr if you don’t currently use Drush, I highly recommend using it, or the Drupal Console.
  • Now, go back to your site, and logged out and then logged in to check if our module works fine.
  • I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.
  • This code can be found and downloaded from https://github.com/codimth/codimth_hashedpassword.

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook