Comparing passwords with crypt() in PHP Comparing passwords with crypt() in PHP php php

Comparing passwords with crypt() in PHP


Following code example may answer your questions.

To generate hashed password using Blowfish, you first need to generate a salt, which starts with $2a$ followed by iteration count and 22 characters of Base64 string.

$salt = '$2a$07$usesomadasdsadsadsadasdasdasdsadesillystringfors';$digest = crypt('rasmuslerdorf', $salt);

Store the whole $digest in database, it has both the salt and digest.

When comparing password, just do this,

  if (crypt($user_input, $digest) == $digest)

You are reusing the digest as salt. crypt knows how long is the salt from the algorithm identifier.


New salt for every password

$password = 'p@ssw0rd';$salt = uniqid('', true);$algo = '6'; // CRYPT_SHA512$rounds = '5042';$cryptSalt = '$'.$algo.'$rounds='.$rounds.'$'.$salt;$hashedPassword = crypt($password, $cryptSalt);// Store complete $hashedPassword in DBecho "<hr>$password<hr>$algo<hr>$rounds<hr>$cryptSalt<hr>$hashedPassword";

Authentication

if (crypt($passwordFromPost, $hashedPasswordInDb) == $hashedPasswordInDb) {    // Authenticated


Quoting from the manual

CRYPT_BLOWFISH - Blowfish hashing with a salt as follows: "$2a$", a two digit cost parameter, "$", and 22 base 64 digits from the alphabet

Note: 22 base 64 digits