A library for generating and validating passwords

Overview

PHP-PasswordLib

Build Status

Build Status

Version

The current version is considered Beta. This means that it is ready enough to test and use, but beware that you should update frequently.

As this software is BETA, Use at your own risk!

About

PHP-PasswordLib aims to be an all-inclusive cryptographic library for all cryptographic needs. It is meant to be easy to install and use, yet extensible and powerful enough for even the most experienced developer.

Installation

PasswordLib supports multiple installation methods.

PHAR

From the downloads tab, download the latest phar build. Then, just require the phar in your code!

require_once '/path/to/PasswordLib.phar';

Composer

Add a composer.json file to your project with the following:

{
    "require": {
        "PasswordLib/PasswordLib": "*"
    }
}

Then, inside that folder, just run php composer.phar install.

Then, in your code, just use the composer autoloader:

require_once 'vendor/.composer/autoload.php';

That's it!

Usage

Most use-cases can simply use the root PasswordLib class.

$lib = new PasswordLib\PasswordLib();
$hash = $lib->createPasswordHash($password);
$boolean = $lib->verifyPasswordHash($password, $hash);

By default, createPasswordHash will create a blowfish hash, which is the most secure available. To create other types, just pass the prefix of the type as a second parameter.

So, to create a drupal hash:

$hash = $lib->createPasswordHash($password, '$S$');

Or to create a SHA512 hash:

$hash = $lib->createPasswordHash($password, '$6$');

It will automatically create a secure salt, and generate the hash.

You can also specify options for the hash. So to use a bcrypt cost of 12,

$hash = $lib->createPasswordHash($password, '$2a$', array('cost' => 12));

verifyPasswordHash will attempt to determine what type of hash is passed in. So one API call can verify multiple types of hashes. This allows for applications to be portable and authenticate against multiple databases with one API.

The PasswordLib class has other API methods for getting random data. Two of particular use are getRandomNumber and getRandomToken.

  • getRandomNumber([$min] [, $max] - gets a secure random integer between the given parameters.

  • getRandomToken($size) returns a random string using base64 characters (a-zA-Z0-9./). This is useful for generating nonce's and tokens to send to clients.

The library also contains other methods for generating random data and hashing data, so look around!

Design Goals

  • 100% Portable

    That means there are no hard (meaning required) dependencies on extensions or non-standard server configurations. Certain configurations will have better performance for certain features, but all configurations should be supported.

  • Well Designed

    The code will use industry standard design patterns as well as follow guidelines for clean and testable code.

  • Well Tested

    That means that the code should be well covered by unit tests. In addition to unit tests, standard test vectors should be run for custom implementations of algorithms to ensure proper behavior.

  • Easy To Install

    PHP-PasswordLib will support three install methods. The first method is a pear based installer. The second is a single file PHAR archive. The third is support via Composer.

  • Easy To Use

    One goal of this system is to provide a simple interface which has secure defaults for standard cryptographic needs (Random token generation, password hashing and verifying, etc). If more power is needed, additional layers of abstraction are available to wire together however is needed.

  • Easy To Extend

    The library should be very easy to extend and add new functionality.

Features

Optional Autoloading

If you include PasswordLib via a PHAR package, it will automatically autoload all of the classes for you, no extra step necessary. Simply:

require 'path/to/PasswordLib.phar';

If you include PasswordLib via a filesystem install, you can use the internal autoloader by either loading the bootstrap.php file, or loading the PasswordLib.php file

require_once 'path/to/PasswordLib/bootstrap.php

or

require_once 'path/to/PasswordLib/PasswordLib.php

You can also use any [PSR-0] 3 autoloader. PasswordLib will automatically detect if an autoloader is setup for its namespace, and will not declare its own if it finds one (it does this by testing if the class PasswordLib\Core\AutoLoader can be found. If so, that means that an autoloader was declared already. If not, it loads the core implementation).

$classLoader = new SplClassLoader('PasswordLib', 'path/to/');
$classLoader->register();

Note that the path you supply is the directory which contains the PasswordLib directory. Not the PasswordLib directory itself.

Secure Random Number/String Generation

PHP-PasswordLib implements a method specified in [RFC 4086 - Randomness Requirements for Security] 2. Basically, it generates randomness from a number of pseudo random sources, and "mixes" them together to get better quality random data out. When you specify the "strength" of random generator, you are actually telling the system which sources you would like to use. The higher the strength, the slower and potentially more fragile the source it will use.

The mixing function is also dependent upon the strength required. For non-cryptographic numbers, a simple XOR mixing function is used (for speed). As strength requirements increase, it will use a SHA512 based mixing function, then a DES based mixing function and finally an AES-128 based mixing function at "High" strength.

And all of this is hidden behind a simple API.

To generate user-readable strings, you can use the PasswordLib class (which generates medium strength numbers by default):

$crypt = new PasswordLib\PasswordLib;
$token = $crypt->getRandomToken(16);

Or you can use the core generator to get more control:

$factory = new PasswordLib\Random\Factory;
$generator = $factory->getHighStrengthGenerator();
$token = $generator->generateString(16);

To generate salts, simple use PasswordLib::getRandomString() or Generator::generate()

Password Hashing And Validation

A number of password hashing algorithms are supported. When creating a new hash, the algorithm is chosen via a prefix (a CRYPT() style prefix). The library will do the rest (salt generation, etc):

$crypt = new PasswordLib\PasswordLib;
$hash = $crypt->createPasswordHash($password, '$2a$'); // Blowfish
$hash = $crypt->createPasswordHash($password, '$S$'); // Drupal

When validating password hashes, where possible, the library will actually auto-detect the algorithm used from the format and verify. That means it's as simple as:

$crypt = new PasswordLib\PasswordLib;
if (!$crypt->verifyPasswordHash($password, $hash)) {
    //Invalid Password!
}

You can bypass the auto-detection and manually verify:

$hasher = new PasswordLib\Password\Implementation\Joomla;
$hash = $hasher->create($password);
if (!$hasher->verify($password, $hash)) {
    //Invalid Hash!
}

Specifications

  • Supported Password Storage Functions

    • APR1 - Apache's internal password function
    • Blowfish - BCrypt
    • Crypt - Crypt DES hashing
    • Drupal - Drupal's SHA512 based algorithm
    • Hash - Raw md5, sha1, sha256 and sha512 detected by length
    • Joomla - Joomla's MD5 based algorithm
    • Crypt MD5 - Support for Crypt's MD5 algorithm
    • PBKDF - A PBKDF implementation (which supports any supported password based key derivation)
    • PHPASS - An implementation of the portable hash from the PHPASS library
    • PHPBB - PHPBB's MD5 based algorithm
    • Crypt SHA256 - Crypt's SHA256 algorithm
    • Crypt SHA512 - Crypt's SHA512 algorithm
  • Supported Random Number Sources

    • CAPICOM - A COM object method call available on Windows systems
    • MTRand - Generation based upon the mt_rand() functions
    • MicroTime - A low entropy source based upon the server's microtime
    • Rand - A low entropy source based upon rand()
    • URandom - Generation from the system's /dev/urandom source
    • UniqID - A low entropy source based upon uniqid()

Library Dependencies:

The only dependency PHP-PasswordLib has to use as a library is the PHP version. It is made to be completely indepedent of extensions, implementing functionality natively where possible.

Required

  • PHP >= 5.3.2

Optional

  • [MCrypt] 1 Support Compiled In

Build (Testing) Dependencies:

These dependencies are necessary to build the project for your environment (including running unit tests, packaging and code-quality checks)

Pear Dependencies

  • PDepend Channel (pear.pdepend.org)

    • pdepend/PHP_Depend >= 0.10.0
  • Phing Channel (pear.phing.info)

    • phing/Phing >= 2.4.0
  • PHPMD Channel (pear.phpmd.org)

    • phpmd/PHP_PMD >= 1.1.0
  • PHPUnit Channel (pear.phpunit.de)

    • phpunit/PHPUnit >=3.5.0
    • phpunit/PHP_CodeBrowser >= 1.0.0
    • phpunit/phpcpd >= 1.3.0
    • phpunit/phploc >= 1.6.0
  • PHP-Tools Channel (pear.php-tools.net)

    • pat/vfsStream >= 0.8.0
  • Default Pear Channel

    • pear/PHP_CodeSniffer >= 1.3.0
    • pear/PHP_UML >= 1.5.0

Note: You can install all of them with the following commands:

pear channel-discover pear.pdepend.org
pear channel-discover pear.phing.info
pear channel-discover pear.phpmd.org
pear channel-discover pear.phpunit.de
pear channel-discover pear.php-tools.net
pear channel-discover components.ez.no
pear channel-discover pear.symfony-project.com

pear install pdepend/PHP_Depend
pear install phpmd/PHP_PMD
pear install pat/vfsStream
pear install PHP_CodeSniffer
pear install PHP_UML
pear install phpunit/PHPUnit
pear install phpunit/PHP_CodeBrowser
pear install phpunit/phpcpd
pear install phpunit/phploc
pear install phing/Phing

PHP Dependencies

  • PHP >= 5.3.2

    • php.ini Settings:
      • phar.readonly = Off
  • PHP Extensions

    • XDebug
    • MCrypt
    • Hash (usually enabled)
    • Phar
    • Zip (For Packaging)
    • BZ2 (For Packaging)
    • XSL (For Documentation)

Security Vulnerabilities

If you have found a security issue, please contact the author directly at [email protected].

Comments
  • Argon2 password with php

    Argon2 password with php

    @ircmaxell Hi,

    Would consider to provide a php code to generate Argon2i and Argon2d password? Right now, it seems only C version is available and not php.

    opened by nimasdj 4
  • unexpected (T_VARIABLE) error

    unexpected (T_VARIABLE) error

    I have a file that contains the following to test the script and make sure it will hash the password and that it is not a fault somewhere else.

    <?php
    require_once "/home/benj545.ath.cx/bocsy/assets/PasswordLib/bootstrap.php";
    
    $password = "password"
    $crypt = new PasswordLib\PasswordLib;
    $hash = $crypt->createPasswordHash($password, '$a2$'); // Blowfish
    echo $hash;
    

    Although when I try to run this script I get the following error which does not occur when I am running on my local machine although happens on my webserver. My webserver is running PHP version 5.4.12 and my localhost is running PHP 5.3.9

    PHP Parse error:  syntax error, unexpected '$crypt' (T_VARIABLE) in /home/benj545.ath.cx/bocsy/test.php on line 5
    
    opened by bens545 3
  • Why the priority on BCMath in BigMath instead of GMP?

    Why the priority on BCMath in BigMath instead of GMP?

    Looking at this page: http://phpseclib.sourceforge.net/math/intro.html I see that GMP gives better performance then BCMath.

    Why then does BigMath::createFromServerConfiguration() have this order?

    if (extension_loaded('bcmath')) {
        return new \PasswordLib\Core\BigMath\BCMath();
    } elseif (extension_loaded('gmp')) {
        return new \PasswordLib\Core\BigMath\GMP();
    } else {
        return new \PasswordLib\Core\BigMath\PHPMath();
    }
    

    I suggest to turn it around. Or are there reasons for priority on bcmath?

    opened by meghuizen 3
  • Add

    Add "set cost"

    Adding the ability to set a "cost" (iterations) for bcrypt. Also included is the ability to get the factory's implementation and set a prefix. Updated some tests for new functionality.

    opened by enygma 3
  • Fix potential modulo-bias in generateString.

    Fix potential modulo-bias in generateString.

    Existing implimentation introduces modulo-bias when the length of $characters does not evenly divide 256. Fortunately, the default character set does evenly divide.

    opened by derekmarcotte 2
  • Shared Host : /dev/urandom is not within the allowed path(s)

    Shared Host : /dev/urandom is not within the allowed path(s)

    Shared Host : /dev/urandom is not within the allowed path(s)
    env debian6 php 5.3 apache2

    diff --git a/URandom.php.original b/URandom.php
    index 8d661f6..3f7d695 100644
    --- a/URandom.php.original
    +++ b/URandom.php
    @@ -54,7 +54,7 @@ class URandom implements \PasswordLib\Random\Source {
          * @return string A string of the requested size
          */
         public function generate($size) {
    -        if ($size == 0 || !file_exists($this->file)) {
    +        if ($size == 0 || !@file_exists($this->file)) {
                 return str_repeat(chr(0), $size);
             }
             $file = fopen($this->file, 'rb');
    
    opened by aborigines 2
  • createPasswordHash with options - master ready for a new beta?

    createPasswordHash with options - master ready for a new beta?

    It seems the PasswordLib->createPasswordHash() call which accepts an options array (which is documented in the README) is only on master currently.

    Is master in a state of flux or is it ready for a new beta release? If a new beta from master could be made, it could be nice to get it onto packagist too.

    ?

    opened by polesen 1
  • Added OpensslRandPseudo random source.

    Added OpensslRandPseudo random source.

    This uses openssl_random_pseudo_bytes. This is suggested for use only with with php5-openssl compiled against LibreSSL:

    OpenSSL copying RNG state on fork: https://github.com/ramsey/uuid/issues/80#issuecomment-188286637 Fixed in LibreSSL: http://opensslrampage.org/post/91910269738/fix-for-the-libressl-prng-issue-under-linux

    Additionally, CVE-2015-8867 was fixed only in versions 5.6.12, 5.5.28, 5.4.44 and above:

    https://bugs.php.net/bug.php?id=70014 http://www.php.net/ChangeLog-5.php

    CVE-2015-8867 does not affect versions compiled against LibreSSL.

    For these reasons, it only is considered a LOW source of randomness, unless it is compiled against LibreSSL.

    The reason for this to exist at all is because of problems with the nature of /dev/urandom. For example, if we cannot open or read the file. openssl_random_pseudo_bytes should never fail.

    opened by derekmarcotte 0
  • Composer install fails

    Composer install fails

    Composer install fails due to following error:

    "PasswordLib/PasswordLib": "*" does not exist

    use

    "PasswordLib/PasswordLib": "dev-master"

    instead

    opened by bendspoons 0
  • PBKDF2 recommendations

    PBKDF2 recommendations

    Hi,

    Is PBKDF2 as binary (having the last parameter of hash_pbkdf2 function as true) stronger and more recommended than hexit? And 1000 iteration is reasonable or still weak?

    opened by nimasdj 0
  • SHA salts shorter than 16

    SHA salts shorter than 16

    I have SHA-256 hashes with a salt of 9 characters. According to what I understand, the spec allows this. However, the library doesn't detect / verify hashes in this format.

    opened by lode 4
  • HHVM (HipHop VM) current limits output to the first 255 bytes of output....

    HHVM (HipHop VM) current limits output to the first 255 bytes of output....

    ... If the prefix exceeds this, the returned string never contains

    any added entropy, nor can it ever grow passed 255 bytes trapping us in an infinite loop if we request a larger string. Concatenating the prefix and the generated should theoretically be faster through the uniqid function, so we'll only concatenate our own if we're running HHVM, as well as have two seperate loops available so we only have to evalute if we're running HHVM once vs every iteration of a singular loop.

    opened by navecommunications 1
Owner
Anthony Ferrara
Anthony Ferrara
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
Realistic PHP password strength estimate library based on Zxcvbn JS

Zxcvbn-PHP is a password strength estimator using pattern matching and minimum entropy calculation. Zxcvbn-PHP is based on the the Javascript zxcvbn p

Ben Jeavons 767 Dec 15, 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
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
Security CSRF (cross-site request forgery) component provides a class CsrfTokenManager for generating and validating CSRF tokens.

Security Component - CSRF The Security CSRF (cross-site request forgery) component provides a class CsrfTokenManager for generating and validating CSR

Symfony 1.5k Jan 3, 2023
A PHP package for validating/generating/formatting an IRS document number (CPF/CNPJ)

A PHP package for validating/generating/formatting an IRS document number (CPF/CNPJ)

null 7 Dec 15, 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 small PHP library for validating VAT identification numbers (VATINs).

VATIN A small PHP library for validating VAT identification numbers (VATINs). Installation This library is available on Packagist: $ composer require

David de Boer 128 Oct 27, 2022
PHP Email address validator - A library for validating emails against several RFC.

EmailValidator A library for validating emails against several RFC. Supported RFCs This library aims to support RFCs: 5321, 5322, 6530, 6531, 6532, 10

Eduardo Gulias Davis 10.7k Jun 13, 2022
A small library for validating International Bankaccount Numbers (IBANs) based on the IBAN Registry provided by SWIFT

A small library for validating International Bankaccount Numbers (IBANs) based on the IBAN Registry provided by SWIFT

Jan Schädlich 69 Dec 18, 2022
Self-hosted platform to keep and share your content: web links, posts, passwords and pictures.

Shaark is a self-hosted platform to keep and share your content: web links, posts, passwords and pictures. All of your data can be private, public or

MarceauKa 482 Dec 30, 2022
Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords.

Laravel Otpify ?? Introduction Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords. Install

Prasanth Jayakumar 2 Sep 2, 2022
A simple package to validate against common passwords and help keep your application secure.

common-passwords A simple package to validate against common passwords and help keep your application secure. composer require crumbls/common-password

Crumbls 4 Oct 16, 2021
Harden request headers, login interface and passwords to increase backend security.

JvMTECH.NeosHardening Package for Neos CMS Harden request headers, login interface and passwords to increase backend security. Installation composer r

Jung von Matt TECH 3 May 4, 2022
MySecureVault is the most secure passwords, notes and files vault on the Internet.

MySecureVault MySecureVault is the most secure passwords, notes and files vault on the Internet. It has been developed with ultimate privacy and secur

MySecureVault 1 Jan 26, 2022
Prevent users from reusing recently used passwords

Laravel Password History Validation Prevent users from reusing recently used passwords. Installation You can install the package via composer: compose

Paul Edward 67 Oct 10, 2022
A validating SQL lexer and parser with a focus on MySQL dialect.

SQL Parser A validating SQL lexer and parser with a focus on MySQL dialect. Code status Installation Please use Composer to install: composer require

phpMyAdmin 368 Dec 27, 2022
Modern PHP validator on steroids for validating forms and/or array's.

Modern PHP Validator - Standalone Validation on Steroids Introduction Head first example Installation Adding fields for validation Execute validation

Kris Kuiper 5 Oct 5, 2022
Tools for working with the SPDX license list and validating licenses.

composer/spdx-licenses SPDX (Software Package Data Exchange) licenses list and validation library. Originally written as part of composer/composer, no

Composer 1.4k Dec 26, 2022