这些是我用于密码加密和密码验证的一些函数。想知道这是否是处理它的好方法。我正在使用 codeigniter 框架。
这是“加密”的功能:
function crypt_pass( $input ){
$salt = substr(sha1(date('r')), rand(0, 17), 22);
$cost = 10;
$hash = '$2y$' . $cost . '$' . $salt;
$pw_and_salt['pw'] = crypt($input, "$hash");
$pw_and_salt['salt'] = $salt;
return $pw_and_salt;
}
我将密码和盐都存储在我的数据库中。这是登录功能:
function login(){
$this->db->select('salt');
$salt = $this->db->get_where('users', array('username' => $this->input->post('username') ) )->row();
$where = array(
'username' => $this->input->post('username'),
'password' => crypt( $this->input->post('password'), '$2y$10$' . $salt->salt),
);
$user = $this->db->get_where('users', $where)->first_row();
if (!$user) {
return FALSE;
}else{
if(!empty($user->activation)){
return 2;
}else if($user && empty($user->activation)){
$this->session->set_userdata('id',$user->id);
$this->session->set_userdata('username',$user->username);
$this->session->set_userdata('first_name',$user->first_name);
return 1;
}
}
}
我的实现方式是否正确?这足够安全吗?
版本 2:不存储盐,而是从数据库中的密码中提取:
function login(){
$this->db->select('password');
$pw = $this->db->get_where('users', array('username' => $this->input->post('username') ) )->row();
$where = array(
'username' => $this->input->post('username'),
'password' => crypt( $this->input->post('password'), $pw->password),
);
$user = $this->db->get_where('users', $where)->first_row();
if (!$user) {
return FALSE;
}else{
if(!empty($user->activation)){
return 2;
}else if($user && empty($user->activation)){
$this->session->set_userdata('id',$user->id);
$this->session->set_userdata('username',$user->username);
$this->session->set_userdata('first_name',$user->first_name);
return 1;
}
}
}
最佳答案
有些地方可以改进,但首先我会推荐使用 PHP 的新功能 password_hash() .此函数将生成一个安全盐并将其包含在生成的哈希值中,因此您可以将其存储在单个数据库字段中。还有一个 compatibility pack对于早期版本。
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
关于您的代码的一些想法:
- 您使用 crypt() 生成一个 BCrypt 散列,因此盐将成为生成的散列的一部分。无需单独存放。
- 可以改进盐的生成,使用操作系统 MCRYPT_DEV_URANDOM 的随机源。
- 如果您将成本因子更改为 9,格式将变得无效,因为 crypt 需要两位数。
关于php - Crypt() 盐生成和密码加密,执行得好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20368038/