Logo
  • PHP
    • HipHop / HHVM
    • Modern PHP
    • PHPStorm
    • LAMP
    • Laravel
    • Composer
    • PDO
  • JavaScript
    • node.js
    • AngularJS
  • CSS
    • SASS
    • “CSS4” (CSS level 4)
  • HTML
  • Git
  • LAMP
  • Vagrant
  • UI / UX
  • Architecture of …
  • Off-Topic
With ♥ from Berlin
September 14, 2013
Chris
PHP
0

How to use the PHP 5.5 password hashing functions

PreviousNext
php

PHP 5.5 introduced some very interesting password hashing functions that will make your life much much easier, the web much much safer and obviously that’s the beginning of better times when it comes to application security. Those functions make it extremely easy to create and verify password hashes. To understand how they work, have a look on this code and try to run it on your PHP 5.5 environment.

Please note: To make these functions available in PHP 5.3.7+ (minimum requirement!) or PHP 5.4+, include the password compatibility library by Anthony Ferrara (who’s the developer of those functions by the way).

 

<?php

// THESE FUNCTIONS WILL WORK WITH PHP 5.5
// if you want to use them with PHP 5.3 or 5.4 you'll need to include
// the lib/password.php file from this project:
// https://github.com/ircmaxell/password_compat/

echo "Please note: These functions need at least PHP 5.3.7<br/>";
echo "You are running PHP ".phpversion();
echo "<br/>";

// hashing & salting a password (salt will be auto-generated)
$pass = 'mysecretpassword';
$hash = password_hash($pass, PASSWORD_DEFAULT);
echo $hash;
echo "<br/>";
echo "Length hash: ".strlen($hash)."<br/>";

// checking if the password fits to the saved hash/salt-string
var_dump(password_verify($pass, $hash));
echo "<br/>";

// checking if the password fits to the saved hash/salt-string
// intentionally using a wrong password
$wrong_pass = 'atotallywrongpassword';
var_dump(password_verify($wrong_pass, $hash));
echo "<br/>";

// getting info from hash string, useful for checking if the hash
// is outdated (happens when your hashes are hashed with cost
// factor 7, but after some time you decide to increase it to 8)
var_dump(password_get_info($hash));
echo "<br/>";

// checking the password rehash function
// same cost factor like before, so the function should return false
$options['cost'] = 10;
var_dump(password_needs_rehash($hash, PASSWORD_DEFAULT, $options));
echo "<br/>";

// we increase the cost factor, so the function should return true
$options['cost'] = 11;
var_dump(password_needs_rehash($hash, PASSWORD_DEFAULT, $options));
echo "<br/>";

// let's rehash a password with the new cost factor from $options:
// (btw 10 is the internal standard)
$hash = password_hash($pass, PASSWORD_DEFAULT, $options);
echo $hash;
echo "<br/>";
echo "Length hash: ".strlen($hash)."<br/>";

// finally, some time tests: cost factor 7
$options['cost'] = 7;
$runtime_start = microtime(true);
password_hash($pass, PASSWORD_DEFAULT, $options);
$runtime_end = microtime(true);
$runtime_total = $runtime_end - $runtime_start;
echo "Runtime with cost factor 7: ".$runtime_total." seconds<br/>";

// finally, some time tests: cost factor 10
$options['cost'] = 10;
$runtime_start = microtime(true);
password_hash($pass, PASSWORD_DEFAULT, $options);
$runtime_end = microtime(true);
$runtime_total = $runtime_end - $runtime_start;
echo "Runtime with cost factor 10: ".$runtime_total." seconds<br/>";

This will generate output like this:

Please note: These functions need at least PHP 5.3.7
You are running PHP 5.3.21
$2y$10$/m.xxwGqroKHnI6/5XrsQOKMmejfFMmOW8JuLnAT.TLbTboyfi1.6
Length hash: 60
bool(true)
bool(false)
array(3) { 
["algo"]=> int(1) 
["algoName"]=> string(6) "bcrypt" 
["options"]=> array(1) { ["cost"]=> int(10) } 
}
bool(false)
bool(true)
$2y$11$/YaA58m4HcKxmzva0AJnceWyeD9pKBSq.dJfpUGbwZgpAxPCoxHRe
Length hash: 60
Runtime with cost factor 7: 0.019093036651611 seconds
Runtime with cost factor 10: 0.14752817153931 seconds

 

PHP 5.5 password hashing summarized:

 

Generate a hash from a real password: [Offical manual page here]
$pass is your password, PASSWORD_DEFAULT is a PHP internal constant that defines the used hashing algorithm (PHP itself might change this when time goes by to keep in that with current server hardware improvements):

password_hash($pass, PASSWORD_DEFAULT);

 

Check password: [Official manual page here]
To check if password $pass (from user login form usually) fits the database-saved hash $hash:

password_verify($pass, $hash);

 

Additionally, for people who know what they to:
Check if your password needs to be rehashed: [Official manual page here]
(because you changed your server hashing cost factor settings): where $hash is the database-saved hash, PASSWORD_DEFAULT (see above) is the PHP internal hash algorithm constant and $options is an array of options, usually only the “cost” key is interesting. Imagine that you were using a cost factor of 8 for years, and now you changed the cost factor to 10 (somewhere in your app’s configs, here in this example represented by this line: $options[‘cost’] = 10;), then this function will check if your database-saved hash needs to be rehashed (via password_hash();) and saved again to the database.

$options['cost'] = 10;
password_needs_rehash($hash, PASSWORD_DEFAULT, $options);

 

Read out the hashing infos from a hash: [Official manual page here]
Every hash created by password_hash() provided extractable information about the used hashing algorithm (in a coded and a human-readable version) and about the used cost factor. Get the info array via:

password_get_info($hash);

 

By the way, all those ultra-modern functions are used in all versions of the php-login script, if you don’t know it yet, have a look here: http://www.php-login.net

 

This article was written quite a while ago (9 years), please keep this in mind when using the information written here. Links, code and commands might be outdated or broken.

Random articles

  • PHPMyAdmin not found after installation ? Here’s a fix (Ubuntu 12.04) !PHPMyAdmin not found after installation ? Here’s a fix (Ubuntu 12.04) !
  • (Links) How to fix an extremely slow Symfony inside a Vagrant box(Links) How to fix an extremely slow Symfony inside a Vagrant box
  • Best introduction to unix command line / bash ever (by André Augusto Costa Santos)Best introduction to unix command line / bash ever (by André Augusto Costa Santos)
  • A quick history of Comic Sans, the most wrongly used font everA quick history of Comic Sans, the most wrongly used font ever
  • Nice gifts for devs: Nerdy playing-cards decksNice gifts for devs: Nerdy playing-cards decks
  • Profiling PHP Applications by Bastian Hofmann (video from PHP UK Conference 2014)Profiling PHP Applications by Bastian Hofmann (video from PHP UK Conference 2014)
  • DEF CON 18 – When your computer got stolen and you can still SSH into it: “Pwned by the 0wner” (22min conference talk)DEF CON 18 – When your computer got stolen and you can still SSH into it: “Pwned by the 0wner” (22min conference talk)
  • Laracon 2013 – Jordi Boggiano: In Depth Composer (47min video)Laracon 2013 – Jordi Boggiano: In Depth Composer (47min video)
  • How to get a single table out of a massive MySQL .sql database backup file (mysql dump splitter)How to get a single table out of a massive MySQL .sql database backup file (mysql dump splitter)
Share this

Leave A Comment Cancel reply

digitalocean coupon

Free $10 coupon for DigitalOcean SSD cloud VPS hosting

DigitalOcean puts out another coupon, this time for free $10 with the code SSD2014. The company offers small and big

Symfony devs: Creator of Symfony framework is hiring (Cologne, Germany)!

Probably one of the most interesting companies for a PHP developer is currently hiring Juniors and Seniors in Cologne, Germany.

set up a local virtual machine for development with vagrant and puphpet / puppet (and ubuntu, linux, php, apache, mysql)

A list of downloadable Vagrant boxes (CentOS 5.9 / 6.4, Ubuntu 12 / 13, Debian 6 / 7 / 7.1 / 7.2)

Offical boxes (directly from Vagrant) Ubuntu 12.04 LTS 32-bit http://files.vagrantup.com/precise32.box Ubuntu 12.04 LTS 64-bit http://files.vagrantup.com/precise64.box   Boxes from puppetlabs.com Seems

ilovepreloaders – A tumblr collection of preloader animations

An excellent collection of preloaders (GIFs, Movies and real ready-to-copy&paste code) here in this wonderful blog: http://ilovepreloaders.tumblr.com/ This thing just

php

[Link] Excellent PHP best practices, 2014 style

Excellent post on This interests me: A collection of useful best practices in modern PHP development, like Redirecting the user

modern-php

Creator of Slim framework and “PHP – The right way” writes book: “Modern PHP”, available 2015

Definitly something every non-superexpert-PHP-developer should have on its books-to-buy-in-2015-list: Josh Lockhart, creator of the legendaray Slim framework and the famous

O’Reilly sells EVERY ebook for -50% right now!

A good chance to grab some IT books: O’Reilly sells every single book in their portfolio with a -50% discount

html6

Is this the first HTML6 specification?

  I just found this very interesting “project” including an active, but unpopular GitHub repo: http://html6spec.com/ https://github.com/OscarGodson/HTML6 Looks like these

vagrant

A super-simple Vagrant LAMP stack bootstrap (installable with one command)

As I have to setup servers inside Vagrant quite often, sometimes 10 times per day, I started to use provisioning:

How Instagram.com works

This article was written quite a while ago (8 years), please keep this in mind when using the information written

1/4

Categories

Search

nginx php 5.5
[Link] Set up Nginx with PHP 5.5 easily
atomic-design
An introduction into Atomic Design, a super-clean way to style web applications
shadow dom
A quick video introduction into Shadow-DOM, the game-changing DOM-subtree-technology
node.js
PayPal drops Java, goes node.js / JavaScript
php
New GitHub repo: simple php-long-polling for creating real-time apps
phpstorm-github-code-color-syntax-theme
Get Github’s code colors in PHPStorm (2014 style)
Dangerous Performance Myths in the Web (video talk by Thomas Lohner, PHPUG Latvia)
(Links) How to fix an extremely slow Symfony inside a Vagrant box
vagrant
Generate Vagrant boxes with Laravel, HipHop, Nginx, WordPress, MySQL, MariaDB, MongoDB, RabbitMQ etc. with one click
phpstorm 7.0 php
PHPStorm 7 has been released!
php
PHP 5.6.0 RC1 is available
gamescom 2014 trailers
GAMESCOM 2014: Awesome Next-Gen ingame graphics
redaktionelle-hochlastseiten
Hochlastseiten mit PHP, MySQL und Apache am Beispiel stern.de (deutscher Artikel)
MINI, an extremely simple barebone PHP application
compress-png
Compress png, jpeg, gif and svg up to 90% with Compressor.io

Tags

apache bash centos composer conference coupon CSS debian fonts framework git GitHub hack HHVM HipHop HTML HTML5 IDE JavaScript JS LAMP laravel linux mod_rewrite MVC MySQL Nginx optimization PHP PHP 5.5 PHP 5.6 phpmyadmin PHPStorm security server SSD Ubuntu UI UX vagrant video virtual machine voucher VPS wordpress
Side-Project: Wordle-Solver:
www.wordle-helper.info

Pages

  • Privacy Policy
 
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT