Joh*_*ith 2 passwords codeigniter pbkdf2 codeigniter-2
我正在研究有关在数据库中存储密码的不同解决方案。读了很多书后,我想我最终会得到PBKDF2。
尽管我对是否应该向 PBKDF2 函数输入盐并将盐存储在一列中并将 PBKDF2 密码存储在另一列中有点困惑。
我还使用 CodeIgniter 并找到了 PBKDF2 的库(https://github.com/HashemQolami/CodeIgniter-PBKDF2-Library),该库声称我不需要单独存储盐。
使用
$pbkdf2['hash']推荐的用户密码注册用户;无需单独储存用户的盐。https://github.com/HashemQolami/CodeIgniter-PBKDF2-Library#step-2
因此,如果我假设正确,我所需要的只是向函数提供密码,然后该函数会处理其余的事情?
我是CodeIgniter PBKDF2 库的创建者。刚刚在 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);
Run Code Online (Sandbox Code Playgroud)
该encrypt()方法返回一个包含 3 个键的数组:salt, password, hash。的值是和hash的串联。saltpassword
此功能允许用户选择如何使用该库,是否使用盐和密码或哈希(盐+密码)。
encrypt():encrypt( string $password [, mixed $good_hash = NULL [, bool $object_output = FALSE]] )
Run Code Online (Sandbox Code Playgroud)
该函数使用给定的盐来生成加密的密码。如果未给出参数,它会使用随机生成的盐。$good_hash $good_hash
因此,如果您单独存储了密码salt,则可以将其作为第二个参数传递给函数来加密给定的密码:
$pbkdf2 = $this->pbkdf2->encrypt($password, $salt);
Run Code Online (Sandbox Code Playgroud)
另一方面salt,如果您已将和的串联存储password到数据库中,则也可以将其作为第二个参数传递给函数:
$pbkdf2 = $this->pbkdf2->encrypt($password, $hash);
Run Code Online (Sandbox Code Playgroud)
该函数将自动中断给定$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
Run Code Online (Sandbox Code Playgroud)
$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...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1967 次 |
| 最近记录: |