northrook/password-validator

一个基于zxcvbn的密码验证器。

dev-main 2024-06-22 13:35 UTC

This package is auto-updated.

Last update: 2024-09-22 14:08:28 UTC


README

zxcvbn-php库的一个包装器。

该软件包提供了一个简单的类,用于验证密码与基于zxcvbn的强度分数。

重要

此软件包仍在开发中。

虽然它被认为是MVP和稳定的,但它仍然可能发生破坏性变更。

计划中的功能

  • 使用zxcvbn-php验证密码。
  • 简单的timeToCrack方法
  • 可选的通过字符串的硬性限制,请参阅问题#74
  • UI组件库集成
  • 可选的<field:password ... >组件的验证。
  • 用于实时验证的JavaScript版本。
  • 可选的`<field:password ...

安装

composer require northrook/password-validator

使用方法

初始化PasswordValidator类,带有一个可选的全局$context数组。

使用validate()方法验证指定的密码,返回一个Result对象。

注意

底层使用了zxcvbn库,尽管它提供了不错的洞察力,但它肯定不是完美的。

在下面的示例中,我们得到了3的分数,尽管在$context中有几个匹配项。

use Northrook\PasswordValidator;

// Optional context for all validations.
$globalContext = [
    'sitename' => 'Example Site',
];   

$validator = new PasswordValidator( $globalContext );

$password = 'example-01-user';
$context  = [
    'username'  => 'Example User',
    'email'     => 'user@example.com',
    'birthdate' => '1980-01-01',
];

$result = $validator->validate( $password, $context ) : Result

Result对象使用zxcvbn-php库验证密码,并设置以下只读属性

$pass:bool       // `true` if the password is strong enough, else `false`.
$strength:int    // The strength score of the password.
$label:string    // A human-readable label for the strength score.
$guesses:int     // The number of guesses required to crack the password.
$warning:?string // A warning message if the password is not strong enough, else `null`.
$suggestions:[]  // A list of suggestions to improve the password.

Result对象还有其他方法

// Validate the password against a given strength score.
$result->validate( int $strength ):bool

// Get the time to crack the password, in seconds by default.
$time = $result->timeToCrack(
    ?string $scenario = 'online_throttling',  // The zxcvbn-php scenario to use.
     string $return = 'RETURN_SECONDS',       // RETURN_SECONDS, RETURN_LABEL, RETURN_BOTH as object{seconds:int, label:string}.
):int|string|obj

$time->seconds; // 173052000000
$time->label;   // "centuries"

许可证

MIT