DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Migrating to password_verify

Migrating to password_verify

Still using MD5 as your hashing algorithm? You may want to change that. We look at migrating from MD5 to something more secure using PHP.

Rob Allen user avatar by
Rob Allen
·
Dec. 11, 18 · Tutorial
Like (1)
Save
Tweet
Share
8.97K Views

Join the DZone community and get the full member experience.

Join For Free

I've recently been updating a website that was written a long time ago that has not been touched in a meaningful way in many years. In addition to the actual work I was asked to do, I took the opportunity to update the password hashing routines.

This site is so old that the passwords are stored using MD5 hashes. and that's not really good enough today. So I included updating to bcrypt hashing with password_hash() and password_verify() in my statement of work.

I've done this process before, but don't seem to have documented it, so thought I'd write down the steps I took in case it helps anyone else.

Updating Existing Passwords in the Database

The first thing I did was hash all the passwords in the database to bcrypt with password_hash. As the current passwords are stored in hashed form, we don't have the original plain-text passwords, so we end up with bcrypt hashes containing the MD5 hashes. This is okay as we can handle this in the login process.

This update is a one-off PHP script:

$sql = 'SELECT id, password FROM user';
$rs = $database->execute($sql);
$rows = $rs->GetArray();
foreach ($rows as $row) {
    $sql = 'UPDATE user SET password = ? WHERE id = ?';
    $database->execute($sql, [
        password_hash($row[['password'], PASSWORD_DEFAULT),
        $row['id'],
    ]);
}
echo "Passwords updated\n";

This website uses ADOdb so I just continued using it. The principles apply regardless of whether you're using PDO or any other database abstraction library.

I also had to update the database schema and change the password column from varchar(32) to varchar(255). The 255 characters is recommended by the PHP manual page as it allows for the algorithm to change again.

Updating Login

The authentication code needs updating to deal with bcrypt passwords. It currently looks like this:

$email = $_POST['email_address'];
$password = $_POST['password'];

$sql = "SELECT * FROM user where email = ? and password = ?";
$rs = $database->Execute($sql, array($email, md5($password)));
if ($rs->RecordCount() == 1) {
    // valid user
    $_SESSION['user'] = $rs->FetchRow();
}


In this code, there is a single step that only retrieves the user if — and only if — the email address and the MD5 of the plain text password match in the database record. If precisely one record is returned, it is assigned to the session.

To use password_verify(), we need a two-step process:

  1. Retrieve the user via email address
  2. Check the retrieved hashed password against the password the user has supplied

Step 1

For the first step, I can retrieve the user by removing the password check from the SQL query:

$sql = "SELECT * FROM user where email = ?";
$rs = $database->Execute($sql, array($email));
if ($rs->RecordCount() == 1) {
    // ..


Step 2

I now need to check the password, which I do with password_hash():

if ($rs->RecordCount() == 1) {
    $user = $rs->FetchRow();
    $validPassword = password_verify($password, $user['password']);
    if ($validPassword) {
        // valid user
        $_SESSION['user'] = $user;
    }
}

This works great for all users who have an updated singly hashed plain text password, but none of my existing users can log in! This is because their bcrypt passwords are an MD5 hash of their plain text password.

To allow all users to log in, we need to also check for an MD5 hash if the password_verify() fails:

    $validPassword = password_verify($password, $user['password']);
    if (!$validPassword) {
        // check for a legacy password
        $validPassword = password_verify(md5($password), $user['password']);
    }
    if ($validPassword) {
        // valid user
        $_SESSION['user'] = $user;

In this code, we MD5 the password supplied by the user and check again with password_verify against the database record. If it succeeds this time, then the credentials are verified.

Now all our users can successfully log in.

In-Place Migrating

As the login process is the only time when we have the user's plain text password available to us, this is the ideal time to migrate the user's password in the database from a hashed MD5 string to a hashed plain text password.

I did this in the code where we checked for the MD5 version, but only if the check was successful:

   $validPassword = password_verify($password, $user['password']);
    if (!$validPassword) {
        // check for a legacy password
        $validPassword = password_verify(md5($password), $user['password']);
        if ($validPassword) {
            // migrate user's record to bcrypt
            $sql = 'UPDATE user SET password = ? WHERE id = ?';
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $database->Execute($sql, [$hashedPassword, $user['id']]);
        }
    }

Now, every time a user logs in with an MD5 hashed password, we will automatically re-hash their plain text password to bcrypt.

Updating Password Creation

Finally, I went through and fixed all the code that created a password in the database. This was in the user admin section and the user's change-password and reset-password pages.

In all cases, I changed:

$password = md5($new_password);

to

$password = password_hash($new_password, PASSWORD_DEFAULT);


password_hash() requires a second parameter which is the algorithm to use. Unless you have a specific reason not to, use PASSWORD_DEFAULT.

That's It

That's all the steps that I went though. I would expect that for applications actively maintained, most if not all have been updated by now, as PHP 5.5 came out in 2009! However, it wouldn't surprise me if there are many sites out there that were built by an agency in the past where the client doesn't actively maintain it, but only asks for updates when changes are required — as in this case.

Database Plain text

Published at DZone with permission of Rob Allen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How Do the Docker Client and Docker Servers Work?
  • Kotlin Is More Fun Than Java And This Is a Big Deal
  • The Role of Data Governance in Data Strategy: Part II
  • 2023 Software Testing Trends: A Look Ahead at the Industry's Future

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: