我是CodeIgniter PBKDF2 Library的创建者。刚刚在 SO 上找到了这个主题,我决定澄清这个库是如何工作的。
以下是文档中的示例代码:
# Load pbkdf2 library into your controller
$this->load->library('pbkdf2');
# Get password, which has been sent via POST method
$password = $this->input->post('password');
# Encrypt the given password using a random generated salt
$pbkdf2 = $this->pbkdf2->encrypt($password);
该encrypt()方法返回一个包含 3 个键的数组salt: 、password、hash。的值是和hash的串联。saltpassword
这个特性让用户可以选择如何使用这个库,是使用盐和密码还是散列(盐+密码)。
方法语法encrypt():
encrypt( string $password [, mixed $good_hash = NULL [, bool $object_output = FALSE]] )
该函数使用给定的盐来生成加密密码。如果没有给出参数,它会使用随机生成的盐。$good_hash $good_hash
所以,如果你已经salt单独存储了,你可以将它作为第二个参数传递给函数来加密给定的密码:
$pbkdf2 = $this->pbkdf2->encrypt($password, $salt);
另一方面,如果您已将salt和的串联存储password到数据库中,您也可以将其作为第二个参数传递给函数:
$pbkdf2 = $this->pbkdf2->encrypt($password, $hash);
该函数将自动打破给定$hash的以获取salt.
因此,您可以将盐和密码的串联存储在一列(默认为 64 个字符)中,然后使用旧存储的密码加密新的给定密码。
把所有的放在一起
在下文中,我将向您展示如何使用此库来注册/登录用户,而无需单独存储盐和密码。
注册用户:
$this->load->library('pbkdf2');
$password = $this->input->post('password');
$pbkdf2 = $this->pbkdf2->encrypt($password);
# Store $pbkdf2['hash'] into User table as the user's password
登录用户:
$this->load->library('pbkdf2');
$username = $this->input->post('username', TRUE);
$password = $this->input->post('password');
# Fetch the stored user's password from the database
$user_password = $this->user_model->get_password_by($username);
# Check whether the User exists
if ($user_password)
{
# Encrypt the new given password by using the old one:
$pbkdf2 = $this->pbkdf2->encrypt($password, $user_password);
# Check whether the new generated password matches the old one
if ($pbkdf2['hash'] === $user_password) {
# Log in the user ...
} else {
# Show an error...
}
} else {
# Show an error...
}