PHP code example of units / password

1. Go to this page and download the library: Download units/password library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

units / password example snippets


use Units\Password\Password;

$passwords = Password::create(['algorithm' => 'argon2id']);

$stored = $passwords->hash($password)->hash;   // store this
$passwords->verify($password, $stored);        // true
$passwords->verify('wrong', $stored);          // false

$stored = $passwords->hash($password)->hash;

// $argon2id$v=19$m=65536,t=4,p=1$…

if ($passwords->verify($password, $stored)) {
    // signed in
}

$passwords->verify($password, '');          // false
$passwords->verify($password, 'nonsense');  // false

if ($passwords->verify($password, $stored) && $passwords->needsRehash($stored)) {
    $stored = $passwords->hash($password)->hash;   // quietly stronger
}

use Units\Password\PasswordResult;

$result = PasswordResult::fromHash($stored);

$result->algorithm;   // 'argon2id'
$result->options;     // ['memory_cost' => 65536, 'time_cost' => 4, 'threads' => 1]
(string) $result;     // the stored value, unchanged

PasswordResult::fromHash('nonsense')->algorithm;   // 'unknown' — a fact, not a crash

Password::create(['algorithm' => 'argon2id', 'options' => ['cost' => 12]])
    ->hash($password)->options;

// ['memory_cost' => 65536, 'time_cost' => 4, 'threads' => 1]  — PHP's defaults

isset($result->options['cost']);    // false — never used
$result->options['memory_cost'];    // 65536 — used

$passwords->algorithms();          // ['argon2id', 'argon2i', 'bcrypt']
$passwords->supports('argon2id');  // true only if this PHP was built with it

Password::create(['algorithm' => 'scrypt']);
// InvalidArgumentException: [password] unsupported algorithm: scrypt - supported: argon2id, argon2i, bcrypt

// an application composing both units
$peppered = Hasher::create()->hmac($password, $pepper)->hash;
$stored   = Password::create(['algorithm' => 'argon2id'])->hash($peppered)->hash;

$row = ['hash' => $stored, 'dna' => $passwords->dna()->toArray()];

Password::schema()->label();     // Password v1.0.0
Password::schema()->version();   // '1.0.0' - which scheme hashed this