这些是我用于密码加密和密码验证的一些功能。想知道这是否是处理它的好方法。我正在使用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:不存储盐,在DB INSTEAD中从密码中提取:
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;
}
}
}
答案 0 :(得分:6)
有一些要点可以改进,但首先我建议使用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);
关于您的代码的一些想法: