Realistic PHP password strength estimate library based on Zxcvbn JS

Related tags

Passwords zxcvbn-php
Overview

Zxcvbn-PHP is a password strength estimator using pattern matching and minimum entropy calculation. Zxcvbn-PHP is based on the the Javascript zxcvbn project from Dropbox and @lowe. "zxcvbn" is bad password, just like "qwerty" and "123456".

zxcvbn attempts to give sound password advice through pattern matching and conservative entropy calculations. It finds 10k common passwords, common American names and surnames, common English words, and common patterns like dates, repeats (aaa), sequences (abcd), and QWERTY patterns.

Build Status Coverage Status Latest Stable Version License

Installation

The library can be installed with Composer by adding it as a dependency to your composer.json file.

Via the command line run: composer require bjeavons/zxcvbn-php

Or in your composer.json add

{
    "require": {
        "bjeavons/zxcvbn-php": "^1.0"
    }
}

Then run composer update on the command line and include the autoloader in your PHP scripts so that the ZxcvbnPhp class is available.

require_once 'vendor/autoload.php';

Usage

use ZxcvbnPhp\Zxcvbn;

$userData = [
  'Marco',
  '[email protected]'
];

$zxcvbn = new Zxcvbn();
$weak = $zxcvbn->passwordStrength('password', $userData);
echo $weak['score']; // will print 0

$strong = $zxcvbn->passwordStrength('correct horse battery staple');
echo $strong['score']; // will print 4

echo $weak['feedback']['warning']; // will print user-facing feedback on the password, set only when score <= 2
// $weak['feedback']['suggestions'] may contain user-facing suggestions to improve the score

Scores are integers from 0 to 4:

  • 0 means the password is extremely guessable (within 10^3 guesses), dictionary words like 'password' or 'mother' score a 0
  • 1 is still very guessable (guesses < 10^6), an extra character on a dictionary word can score a 1
  • 2 is somewhat guessable (guesses < 10^8), provides some protection from unthrottled online attacks
  • 3 is safely unguessable (guesses < 10^10), offers moderate protection from offline slow-hash scenario
  • 4 is very unguessable (guesses >= 10^10) and provides strong protection from offline slow-hash scenario

Acknowledgements

Thanks to:

Comments
  • Discrepancy with original Dropbox JS library

    Discrepancy with original Dropbox JS library

    The phrase nothingtoshare scores a 3 on the JS library (can check with https://dl.dropboxusercontent.com/u/209/zxcvbn/test/index.html). However, this version gives a score of 0:

    $strength = {array} [6]
     crack_time = 18.85575
     calc_time = 0.031842947006226
     password = "nothingtoshare"
     entropy = 18.524645010213
     match_sequence = {array} [3]
     score = 0
    

    Similarly n0th1ngt0sh@re also scores 3, but only a 1 here:

    $strength = {array} [6]
     crack_time = 509.10525
     calc_time = 0.059408903121948
     password = "n0th1ngt0sh@re"
     entropy = 23.279532512376
     match_sequence = {array} [3]
      0 = {ZxcvbnPhp\Matchers\L33tMatch} [13]
       sub = {array} [3]
       subDisplay = "0 -> o, 1 -> i, 0 -> o, @ -> a"
       l33t = true
       dictionaryName = "english"
       rank = 155
       matchedWord = "nothing"
       password = "n0th1ngt0sh@re"
       begin = 0
       end = 6
       token = "n0th1ng"
       pattern = "dictionary"
       entropy = null
       cardinality = null
      1 = {ZxcvbnPhp\Matchers\L33tMatch} [13]
      2 = {ZxcvbnPhp\Matchers\L33tMatch} [13]
     score = 1
    

    Not sure if the issue is here or with the DropBox lib.

    opened by aramonc 32
  • 32-bit compatibility

    32-bit compatibility

    At least 2 tests are failing on 32-bit computer

    There were 2 errors:
    1) ZxcvbnPhp\Test\Matchers\MatchTest::testBinomialMirrorIdentity
    TypeError: intdiv(): Argument #1 ($num1) must be of type int, float given
    /builddir/build/BUILDROOT/php-bjeavons-zxcvbn-php-1.3.0-1.fc35.noarch/usr/share/php/ZxcvbnPhp/Matchers/BaseMatch.php:158
    /builddir/build/BUILDROOT/php-bjeavons-zxcvbn-php-1.3.0-1.fc35.noarch/usr/share/php/ZxcvbnPhp/Matchers/BaseMatch.php:130
    /builddir/build/BUILD/zxcvbn-php-5268743bffbb8cd182c98a4e79d6ed87004a6621/test/Matchers/MatchTest.php:50
    2) ZxcvbnPhp\Test\Matchers\MatchTest::testBinomialPascalsTriangleIdentity
    TypeError: intdiv(): Argument #1 ($num1) must be of type int, float given
    /builddir/build/BUILDROOT/php-bjeavons-zxcvbn-php-1.3.0-1.fc35.noarch/usr/share/php/ZxcvbnPhp/Matchers/BaseMatch.php:158
    /builddir/build/BUILDROOT/php-bjeavons-zxcvbn-php-1.3.0-1.fc35.noarch/usr/share/php/ZxcvbnPhp/Matchers/BaseMatch.php:130
    /builddir/build/BUILD/zxcvbn-php-5268743bffbb8cd182c98a4e79d6ed87004a6621/test/Matchers/MatchTest.php:62
    ERRORS!
    
    
    opened by remicollet 19
  • php 8.1 support

    php 8.1 support

    I maintain Password Tools, a free opensource add-on for XenForo forum software which uses this library to offer useful password complexity checks.

    As part of updating my code to support php 8.1, this library was identified as having compatibility issues.

    This change does the following;

    • Document a test case which fails on php 7.2/7.3/7.4/8.0 as-is
    • Apply php 7.2+ compatible type hinting to drive discovery of bad type handling
      • getGuesses was documented as returning int but could sometimes return a float. This behaviour was corrected, which required adjusting some tests. I failed to see how it returning a float value is very useful.
    • Use the null coalescing operator in a few spots to cleanup the code, and then pick non-null defaults which work with the increasingly type-strict php
    • A number of php 8.1 compatibility changes, mostly around using null on internal functions which no longer permit it
    opened by Xon 7
  • Fix L33tMatch constructor to avoid setting the sub array to null

    Fix L33tMatch constructor to avoid setting the sub array to null

    This should fix a potential PHP warning:

    • foreach() argument must be of type array|object, null given in .../vendor/bjeavons/zxcvbn-php/src/Matchers/L33tMatch.php on line 214
    opened by lmcnearney 6
  • Add php-7.4 and nightly version tests

    Add php-7.4 and nightly version tests

    Changed log

    • Add the php-7.4 and php-nightly tests.
    • Let php-nightly allow to be failed because nobody can guarantee that unstable PHP version will be successful on every Travis CI build.
    opened by peter279k 4
  • Fix user inputs incorrectly affecting scores

    Fix user inputs incorrectly affecting scores

    Case 1: User input having named keys

    It's not uncommon to want to take things like a user's name, username, email address, and other user metadata into account when evaluating password strength. These items may already already be available in a string-keyed array such as ['name' => 'bob', 'email' => '[email protected]']. The present implementation will use the string key as the input rank, which causes an error when attempting to take the log() of it.

    This is fixed by setting the rank of any user input that has a string key to whatever its numerical position in the user input array is.

    Case 2: Matching user input with rank 0 scoring incorrectly

    correct horse battery staple with no user input would score a 4, but the same password with ['c'] as the user input changes the score to 0 (which is obviously not correct). This is because a rank of 0 causes an entropy score of -INF, which causes the crack time to evaluate to 0.

    This is fixed by ensuring the minimum rank that can be assigned to a value is 1. Any reasonable number would work, but 1 seemed like a fair default, since the default behavior is to use the array index, and 1 is the lowest nonzero positive integer.

    opened by michaelmoussa 4
  • Uncaught Error: [] operator not supported for strings

    Uncaught Error: [] operator not supported for strings

    PHP Fatal error: Uncaught Error: [] operator not supported for strings in /vendor/bjeavons/zxcvbn-php/src/Matchers/L33tMatch.php:55

    any ideas how to fix this ?

    I'm running PHP 7.1.0

    I already try : $result['sub_display'][] = "{$password[$i]} -> $t";

    but I keep getting the same error :(

    Stack trace:
    #0 //vendor/bjeavons/zxcvbn-php/src/Matcher.php(27): ZxcvbnPhp\Matchers\L33tMatch::match('T3H-1337-P@$$', Array)
    #1 //vendor/bjeavons/zxcvbn-php/src/Zxcvbn.php(53): ZxcvbnPhp\Matcher->getMatches('T3H-1337-P@$$', Array)
    #2 //vendor/phpauth/phpauth/Auth.php(187): ZxcvbnPhp\Zxcvbn->passwordStrength('T3H-1337-P@$$')
    #3 /index.php(25): PHPAuth\Auth->register('[email protected]', 'T3H-1337-P@$$', 'T3H-1337-P@$$')
    #4 {main}
      thrown in //vendor/bjeavons/zxcvbn-php/src/Matchers/L33tMatch.php on line 55
    
    opened by fidel95 3
  • Add user data usage example to readme

    Add user data usage example to readme

    Without documented usage of user data argument, php devs would default to passing the array such as

    ['Marco', '[email protected]']
    

    which fails at dictionary matcher when computing a logarithm of string.

    opened by Mikulas 3
  • Password score from JavaScript ist not the same

    Password score from JavaScript ist not the same

    Hi, the password score of JavaScript is not the same as in PHP. I guess that should not be like that?

    PHP

    array:6 [
      "password" => "1111"
      "score" => 0
    ]
    array:6 [
      "password" => "Monday"
      "score" => 0
    ]
    array:6 [
      "password" => "Mond!ay"
      "score" => 2
    ]
    

    JavaScript

    {
      "password": "111",
      "score": 0
    }
    {
      "password": "Monday",
      "score": 1
    }
    {
      "password": "Mond!ay",
      "score": 2
    }
    
    opened by Cyb10101 2
  • PHP 7.1.3: error

    PHP 7.1.3: error "[] operator not supported for strings"

    Since PHP 7.1.3: this code doesn't work:

    $zxcvbn = new Zxcvbn();
    $strength = $zxcvbn->passwordStrength("secret");
    

    Error message: "[] operator not supported for strings"

    Trace: bjeavons\zxcvbn-php\src\ZxcvbnPhp\Matchers\L33tMatch.php:55 bjeavons\zxcvbn-php\src\ZxcvbnPhp\Matcher.php:27 bjeavons\zxcvbn-php\src\ZxcvbnPhp\Zxcvbn.php:53

    opened by ctoesca 2
  • PHP 7.1 Issue: [] operator not supported for strings

    PHP 7.1 Issue: [] operator not supported for strings

    When using the library with PHP 7.1, I get this error: PHP Fatal error: Uncaught Error: [] operator not supported for strings in /home/webuser/websites/config.schokokeks.org/htdocs/vendor/bjeavons/zxcvbn-php/src/Matchers/L33tMatch.php:55

    The line ist: $result['sub_display'][] = "$password[$i] -> $t";

    PHP 7.1 expands the in-string-variable as $password[$i] which is not allowed for strings.

    opened by bwurst 2
  • Fix type error

    Fix type error

    This fix Uncaught TypeError: factorial(): Return value must be of type int, float returned. If the $nparameter in factorial() is bigger than 20, it will cause type error because PHP converts int to float.

    Demonstration: https://onlinephp.io/c/3bbad

    opened by pulzarraider 4
  • score 0 but no warning

    score 0 but no warning

    I don't know if this is a bug or my misunderstanding of the comment in the example, 'echo $weak['feedback']['warning']; // will print user-facing feedback on the password, set only when score <= 2', but I tested with a dictionary word and got back a score of 0 with no warning set:

    ''' Feb 18 11:43:13 admin php: [password] => everything ... Feb 18 11:43:13 admin php: [sequence] => Array Feb 18 11:43:13 admin php: ( Feb 18 11:43:13 admin php: [0] => ZxcvbnPhp\Matchers\DictionaryMatch Object Feb 18 11:43:13 admin php: ( Feb 18 11:43:13 admin php: [pattern] => dictionary Feb 18 11:43:13 admin php: [dictionaryName] => us_tv_and_film Feb 18 11:43:13 admin php: [rank] => 123 Feb 18 11:43:13 admin php: [matchedWord] => everything Feb 18 11:43:13 admin php: [reversed] => Feb 18 11:43:13 admin php: [l33t] => Feb 18 11:43:13 admin php: [password] => everything Feb 18 11:43:13 admin php: [begin] => 0 Feb 18 11:43:13 admin php: [end] => 9 Feb 18 11:43:13 admin php: [token] => everything Feb 18 11:43:13 admin php: ) Feb 18 11:43:13 admin php: Feb 18 11:43:13 admin php: ) ... Feb 18 11:43:13 admin php: [score] => 0 Feb 18 11:43:13 admin php: [feedback] => Array Feb 18 11:43:13 admin php: ( Feb 18 11:43:13 admin php: [warning] => Feb 18 11:43:13 admin php: [suggestions] => Array Feb 18 11:43:13 admin php: ( Feb 18 11:43:13 admin php: [0] => Add another word or two. Uncommon words are better. Feb 18 11:43:13 admin php: ) Feb 18 11:43:13 admin php: Feb 18 11:43:13 admin php: ) '''

    In our project I made the error to check if feedback warning was set as an indication of a score <= 2, so this allowed bypassing the dictionary check - clearly my error, but maybe is a condition that wasn't supposed to happen?

    opened by jnorell 0
  • Use gettext for translation support and add french translation

    Use gettext for translation support and add french translation

    Hello,

    I'm currently working on French support and this second PR add gettext usage to allow warning and suggestion messages translation. My modifications:

    • use dgettext() to translate warning and suggestion messages from custom text domain ZxcvbnPhp. Note: TimeEstimator::displayTime() method was simplified using dngettext() that handle plural forms.
    • Add Locales directory to store translation stuff
    • Bind ZxcvbnPhp text domain to Locales directory in Zxcvbn class constructor
    • Add extract_messages.sh script that handle messages extractions using xgettext and generate/update Locales/zxcvbn-php.pot file
    • Add french translation in Locales/fr_FR.UTF8 directory

    This solution permit to easily integrate this library in PHP application that already use gettext for translation. Other applications just have to set locale by setting LANGUAGE environment variable or using setlocale() function.

    opened by brenard 0
  • SpatialMatch: Add AZERTY keyboard support

    SpatialMatch: Add AZERTY keyboard support

    Hello,

    I'm currently working on French support and this first PR add AZERTY keyboard layout support in SpatialMatch. My modifications:

    • data-scripts/build_keyboard_adjacency_graphs.py:
      • switch to unicode to allow to handle not-ascii characters in keyboad layouts
      • make some assertion errors more explicit
      • add AZERTY keyboard layout
    • src/Matchers/SpatialMatch.php: add AZERTY keyboard layout
    • src/Matchers/adjacency_graphs.json: update it using new build_keyboard_adjacency_graphs.py script to add AZERTY keyboard layout
    opened by brenard 5
  • [feature] Dictionnary location

    [feature] Dictionnary location

    Hello,

    Dictionary location is hard-coded in code. As I'm using composer to install/update, I can't update it. Could you please allow a parameter to be able to specify dictionary location?

    thanks

    opened by abonne01 0
Releases(1.3.1)
Owner
Ben Jeavons
Ben Jeavons
Python implementation of the portable PHP password hashing framework

Portable PHP password hashing framework implemented in Python. This Python implementation meant to be an exact port of the the original PHP version.

Rez 46 Jul 19, 2022
PHP Library to generate random passwords

Password Generator Library Simple library for generating random passwords. Requirements PHP >= 7.1 We only support PHP 7.3+ Installation Install Compo

Daniel Platt 256 Dec 9, 2022
A library for generating and validating passwords

PHP-PasswordLib Build Status Version The current version is considered Beta. This means that it is ready enough to test and use, but beware that you s

Anthony Ferrara 371 Nov 24, 2022
Compatibility with the password_* functions that ship with PHP 5.5

password_compat This library is intended to provide forward compatibility with the password_* functions that ship with PHP 5.5. See the RFC for more d

Anthony Ferrara 2.2k Dec 30, 2022
Validates passwords against PHP's password_hash function using PASSWORD_DEFAULT. Will rehash when needed, and will upgrade legacy passwords with the Upgrade decorator.

Password Validator Password Validator validates password_hash generated passwords, rehashes passwords as necessary, and will upgrade legacy passwords.

Jeremy Kendall 142 Dec 25, 2022
GenPhrase is a secure passphrase generator for PHP applications.

About GenPhrase is a secure passphrase generator for PHP applications. GenPhrase is based on passwdqc's pwqgen program. See http://www.openwall.com/pa

timoh 110 Nov 30, 2022
Industrial-strength annotations for PHP

php-annotations Source-code annotations for PHP. Copyright (C) 2011-2015 Rasmus Schultz [email protected] https://github.com/php-annotations/php-anno

php-annotations 138 Dec 29, 2022
DropItem3D - PocketMine-MP plugin to be able to see drop items realistic.

DropItem3D - PocketMine-MP plugin to be able to see drop items realistic.

ぼい 12 Jun 2, 2022
This example shows how to estimate pi, using generated random numbers that uniformly distributed.

php-estimatepi This example shows how to estimate pi, using generated random numbers that uniformly distributed. Every pair of numbers produced will b

Oğuzhan Cerit 1 Nov 26, 2021
ATOS is a locally hosted application that allows you to easily manage clients/projects, generate invoices against backlogs, and estimate taxes.

Built by freelancer ??‍♂️, for freelancer ?? ?? ???? - ATOS is a locally hosted application that allows you to easily manage clients/projects, generate invoices against backlogs, and estimate taxes.

Jon Belelieu 33 Dec 27, 2022
Laravel Users (Roles & Permissions, Devices, Password Hashing, Password History).

LARAVEL USERS Roles & Permissions Devices Password Hashing Password History Documentation You can find the detailed documentation here in Laravel User

Pharaonic 8 Dec 14, 2022
🔒 Password Exposed Helper Function - Check if a password has been exposed in a data breach.

?? Password Exposed Helper Function This PHP package provides a password_exposed helper function, that uses the haveibeenpwned.com API to check if a p

Jordan Hall 212 Oct 24, 2022
User authentication REST API with Laravel (Register, Email verification, Login, Logout, Logged user data, Change password, Reset password)

User Authentication API with Laravel This project is a user authentication REST API application that I developed by using Laravel and MySql. Setup Fir

Yusuf Ziya YILDIRIM 3 Aug 23, 2022
Gestor de Contraseñas basado en Laravel 8 + PHP 8 + MySQL 8. Self-hosted Password Manager based on Laravel 8 + PHP 8 + MySQL 8.

English Gestor de Contraseñas Esta aplicación permite una gestión completa de contraseñas para múltiples tipos de servicios (web, ssh, teléfonos, wifi

Lito 134 Jan 2, 2023
PHP web based Password Manager for business and personal use.

sysPass - Systems Password Manager Join us in the Gitter chat room: PHP web based Password Manager for business and personal use. AES-256 encryption i

RubénD 896 Dec 26, 2022
CocoPass is a password management system based on Laravel5.3.

CocoPass is a password management system based on Laravel5.3. You can safely and easily store your password here. If course, it is the first version.

Poria 14 Sep 28, 2021
laminas-password-validator provides a validator for character-set based input validation.

laminas-password-validator laminas-password-validator provides a validator for character-set based input validation. Installation composer require pra

null 1 Mar 8, 2022
Laravel breeze is a PHP Laravel library that provides Authentication features such as Login page , Register, Reset Password and creating all Sessions Required.

About Laravel breeze To give you a head start building your new Laravel application, we are happy to offer authentication and application starter kits

null 3 Jul 30, 2022
A password policy enforcer for PHP and JavaScript

PasswordPolicy A tool for checking and creating password policies in PHP and JS. Installation Use composer to setup an autoloader php composer.phar in

Anthony Ferrara 74 Dec 2, 2022
Python implementation of the portable PHP password hashing framework

Portable PHP password hashing framework implemented in Python. This Python implementation meant to be an exact port of the the original PHP version.

Rez 46 Jul 19, 2022