php 随机盐值,加密并随机生成盐

本文介绍了一个使用bcrypt算法的PHP类,用于安全地存储和验证密码。类中包含生成盐、生成哈希和验证密码的功能。bcrypt通过结合随机盐和工作量因子确保即使相同密码也会生成不同哈希,从而提高安全性。当提供正确的密码时,验证功能会返回true,否则返回false。随机盐的作用在于使得每次哈希过程都是唯一的,即使攻击者知道哈希也无法轻易破解原始密码。
摘要由CSDN通过智能技术生成

所以我正在尝试bcrypt。我有一类(如下所示,该类来自http://www.firedartstudios.com/articles/read/php-

security-how-to-safe-store-your-

passwords),其中包含3个功能。第一个是生成随机的Salt,第二个是使用第一个生成的Salt生成哈希,最后一个是通过将提供的密码与哈希密码进行比较来验证所提供的密码。

/* Bcrypt Example */

class bcrypt {

private $rounds;

public function __construct($rounds = 12) {

if(CRYPT_BLOWFISH != 1) {

throw new Exception("Bcrypt is not supported on this server, please see the following to learn more: http://php.net/crypt");

}

$this->rounds = $rounds;

}

/* Gen Salt */

public function genSalt() {

/* openssl_random_pseudo_bytes(16) Fallback */

$seed = '';

for($i = 0; $i < 16; $i++) {

$seed .= chr(mt_rand(0, 255));

}

/* GenSalt */

$salt = substr(strtr(base64_encode($seed), '+', '.'), 0, 22);

/* Return */

return $salt;

}

/* Gen Hash */

public function genHash($password) {

/* Explain '$2y$' . $this->rounds . '$' */

/* 2a selects bcrypt algorithm */

/* $this->rounds is the workload factor */

/* GenHash */

$hash = crypt($password, '$2y$' . $this->rounds . '$' . $this->genSalt());

/* Return */

return $hash;

}

/* Verify Password */

public function verify($password, $existingHash) {

/* Hash new password with old hash */

$hash = crypt($password, $existingHash);

/* Do Hashs match? */

if($hash === $existingHash) {

return true;

} else {

return false;

}

}

}

/* Next the Usage */

/* Start Instance */

$bcrypt = new bcrypt(12);

/* Two create a Hash you do */

echo 'Bcrypt Password: ' . $bcrypt->genHash('password');

/* Two verify a hash you do */

$HashFromDB = $bcrypt->genHash('password'); /* This is an example you would draw the hash from your db */

echo 'Verify Password: ' . $bcrypt->verify('password', $HashFromDB);

?>

现在,例如,如果我生成带有“密码”的哈希,我将得到一个哈希密码,该密码采用了随机生成的Salt。接下来,如果我再次输入“

password”并使用验证功能,我将得到true表示密码匹配。如果输入错误的密码,我将得到错误的密码。我的问题是这怎么可能?随机生成的盐又如何呢?怎么没有效果呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值