如何使用自定义的密码加密和验证方法?从网上找到了解决办法,现记录下来,一方面加深印象,另一方面写成blog备查。
从这篇文章可以了解laravel的认证流程:http://www.tuicool.com/articles/Av2aMb2。
按照文章中的办法,在app下新建文件夹hash,然后新建两个类文件:EloquentUserProvider.php和Security.php
Security.php内容:
namespace App\hash;
use Illuminate\Contracts\Hashing\Hasher;
/**
* 加密类库,移植自Yii2.0的Security类
*/
class Security implements Hasher
{
public $passwordHashCost = 13;
private $_useLibreSSL;
private $_randomFile;
/**
* Generates specified number of random bytes.
* Note that output may not be ASCII.
* @see generateRandomString() if you need a string.
*
* @param integer $length the number of bytes to generate
* @return string the generated random bytes
* @throws InvalidParamException if wrong length is specified
* @throws Exception on failure.
*/
public function generateRandomKey($length = 32)
{
if (!is_int($length)) {
throw new Exception('First parameter ($length) must be an integer');
}
if ($length < 1) {
throw new Exception('First parameter ($length) must be greater than 0');
}
// always use random_bytes() if it is available
if (function_exists('random_bytes')) {
return random_bytes($length);
}
// The recent LibreSSL RNGs are faster and likely better than /dev/urandom.
// Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL.
// https://bugs.php.net/bug.php?id=71143
if ($this->_useLibreSSL === null) {
$this->_useLibreSSL = defined('OPENSSL_VERSION_TEXT')
&& preg_match('{^LibreSSL (\d\d?)\.(\d\d?)\.(\d\d?)$}', OPENSSL_VERSION_TEXT, $matches)
&& (10000 * $matches[1]) + (100 * $matches[2]) + $matches[3] >= 20105;
}
// Since 5.4.0, openssl_random_pseudo_bytes() reads from CryptGenRandom on Windows instead
// of using OpenSSL library. LibreSSL is OK everywhere but don't use OpenSSL on non-Windows.
if ($this->_useLibreSSL
|| (
DIRECTORY_SEPARATOR !== '/'
&& substr_compare(PHP_OS, 'win', 0, 3, true) === 0
&& function_exists('openssl_random_pseudo_bytes')
)
) {
$key = openssl_random_pseudo_bytes($length, $cryptoStrong);
if ($cryptoStrong === false) {
throw new Exception(
'openssl_random_pseudo_bytes() set $crypto_strong false. Your PHP setup is insecure.'
);
}
if ($key !== false && StringHelper::byteLength($key) === $length) {
return $key;
}
}
// mcrypt_create_iv() does not use libmcrypt. Since PHP 5.3.7 it directly reads
// CryptGenRandom on Windows. Elsewhere it directly reads /dev/urandom.
if (function_exists('mcrypt_create_iv')) {
$key = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);