yarri / password-hashing-machine
使用必需(已注册)的散列算法进行密码散列和检查的工具。它可以处理更多(旧版)的散列算法。
v1.0
2021-10-03 10:28 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- atk14/tester: *
- yarri/my-blowfish: ^1.4
This package is auto-updated.
Last update: 2024-08-29 05:38:05 UTC
README
PasswordHashingMachine 是一个工具,用于使用必需的散列算法进行密码散列和检查,这些算法必须从外部注册。
可以向 PasswordHashingMachine 注册更多散列算法,以便也能成功处理旧版散列。
用法
1. 创建散列机
$hasher = new Yarri\PasswordHashingMachine();
2. 添加一个或多个散列算法
// $hasher->addAlgorithm(
// callback $hash_callback,
// callback $is_hash_callback,
// callback $check_password_callback
// );
第一个添加的算法也是默认的散列算法。
// default hashing algorithm - bcrypt
$hasher->addAlgorithm(
function($password){ return password_hash($password,PASSWORD_BCRYPT); },
function($password){ return !password_needs_rehash($password,PASSWORD_BCRYPT); },
function($password,$hash){ return password_verify($password,$hash); }
);
添加您应用程序中需要的其他旧版散列算法。
// algorithm for md5 hashes with common salt
$hasher->addAlgorithm(
function($password){ return md5(SITE_KEY.$password); },
function($password){ return preg_match('/^[0-9a-f]{32}$/',$password); },
function($password,$hash){ return md5(SITE_KEY.$password) === $hash; }
);
// algorithm for md5 hashes
$hasher->addAlgorithm(
function($password){ return md5($password); },
function($password){ return preg_match('/^[0-9a-f]{32}$/',$password); },
function($password,$hash){ return md5($password) === $hash; }
);
实际上,对于提供十六进制散列的算法,如 md5、sha1、sha2,只需要第一个回调。
$hasher->addAlgorithm(
function($password){ return sha1($password); }
);
3. 使用机器
// hashing passwords
$hasher->hash("secret"); // e.g. '$2a$06$rLxnps2CuGC/9BPCq3ms..7uaWETN6GPiVMXYYGWqdQoMZsDQ/kFG'
$hasher->hash('$2a$06$rLxnps2CuGC/9BPCq3ms..7uaWETN6GPiVMXYYGWqdQoMZsDQ/kFG'); // rehash! e.g. '$2y$10$XPuxlYvtelPKTpYtBpeAxOEuidftLo/kGkmmZgtWCFehvWz2N43wy'
$hasher->hash(""); // e.g. '$2y$10$FZQFYFamZjnrUr1XvIdGTevA.iLQNSYvHXrP3LETn67AEGreuYCwe'
// hashing password but preserving valid hashes or empty parameters
$hasher->filter("secret"); // e.g. '$2a$06$rLxnps2CuGC/9BPCq3ms..7uaWETN6GPiVMXYYGWqdQoMZsDQ/kFG'
$hasher->filter('$2a$06$rLxnps2CuGC/9BPCq3ms..7uaWETN6GPiVMXYYGWqdQoMZsDQ/kFG'); // '$2a$06$rLxnps2CuGC/9BPCq3ms..7uaWETN6GPiVMXYYGWqdQoMZsDQ/kFG'
$hasher->filter(""); // ""
$hasher->filter(null); // null
// checking hashes
$hasher->isHash($hash); // true
$hasher->isHash("something"); // false
$hasher->isHash(""); // false
// verifying passwords
$hasher->verify($password,$hash); // true or false
验证成功后,可以检测到旧版散列,并可以使用当前散列算法轻松地重新散列密码。
$hash = $user->getPasswordHash();
if($hasher->verify($password,$hash,$is_legacy_hash)){
// the user is verified
if($is_legacy_hash){
// transparent password re-hashing using the current hashing algorithm
$current_hash = $hasher->hash($password);
$user->setPasswordHash($current_hash);
}
}
安装
安装 PasswordHashingMachine 的最佳方式是使用 Composer
composer require yarri/password-hashing-machine
许可证
PasswordHashingMachine 是在 MIT 许可证下免费软件的 分发条款