Sample Header Ad - 728x90

Issue with hash storage resulting from password_verify() output

1 vote
0 answers
63 views
Consider the following code:
$random_token = random_bytes(32);

$token_hash = password_hash(
  $random_token,
  PASSWORD_DEFAULT
);

$token_base64 = sodium_bin2base64(
  $random_token,
  SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING
);
$token_hash is then stored in a DB field of type LONGTEXT of the collation utf8mb4_unicode_ci. You do so by making a normal insert value using PDO, and to connect with PDO, you use:
$pdo = new PDO(
                dsn:      "mysql:host=host;dbname=db_name;charset=utf8mb4",
                username: 'username',
                password: 'password',
                options:  [
                              // Throw PDO Exception in case of any error
                              PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                              // Fetch the obtained result as associative array by default
                              PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
                          ]
            );
Upon retrieval of the token as base64-encoded URL parameter, you then retrieve the hash from the database using the same PDO connection syntax as above, and then do:
$random_token = sodium_base642bin(
  $token_base64,
  SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING
); 

$result = password_hash($random_token,$token_hash);
In like 10% of the cases, we get false for $result. How can this be? Are we maybe using the wrong collation / charset? Is it a problem that the PDO instance uses a slightly different charset vs the collation of the concerned field? ***UPDATE OF A CASE WHICH FAILED***: An example of a failed hash verification occurred with this hash here: $2y$10$BkpF2otty42SSZS4dczmkeTJk7FJeqgt0D3oCuuOuqCKZG97OZtGu
Asked by DevelJoe (163 rep)
Apr 25, 2023, 12:10 AM
Last activity: May 15, 2023, 08:59 PM