如何使用 PHP password_hash 函数从数据库散列所有密码

How to hash all passwords from DB using PHP password_hash function

是否有任何可能的方法 运行 使用 password_hash() 函数的查询来更改我的用户 table 的所有现有密码?

我正在使用 CI 但根本无法使用!

My model

public function EncryptDB($filters = NULL){
     $ci =& get_instance();
     $ci->load->helper('hash');
     $query = "UPDATE users SET password = {hash_password(password)}";
     $sql = $this->db->query($query);

}

*请注意,我正在加载自定义 helper 对其进行哈希处理。

My helper

function hash_password($password){
        $configs = array(
            "cost" => 10 # custo de processamento (10 -> default)
        );
        $password = password_hash($password, PASSWORD_DEFAULT, $configs);

        return $password;
    }

My controller

public function EncryptDB(){
             if($this->UsersDAO->EncryptDB()){
                  echo 'done';
             } else {
                  echo 'error';
             }
        }

试试这个解决方案。

  1. 此解决方案假定 users table 有一个名为 id 的主键。
  2. 我实际上没有 run/test 这个代码。但无论如何,它应该能让您了解如何解决这个问题。
  3. 此代码 运行 位于事务内,因此如果一条记录更新失败,则 none 将更新。
  4. 此代码可能应该 运行 只有一次,固定 table。

    function updatePasswords(){

    $this->db->trans_start();
        $offset = 0;
        do{
            $selectQuery = $this->db
                                ->limit(100, $offset)
                                ->get('users');
            $results = $selectQuery->result();
    
            foreach ($results as $user){
                $configs = array(
                    "cost" => 10 # custo de processamento (10 -> default)
                );
                $hashedPassword = password_hash($user->password, PASSWORD_DEFAULT, $configs);
                $this->db
                    ->set('password', $hashedPassword)
                    ->where('id', $user->id)
                    ->update('users');
            }
    
            $offset += $selectQuery->num_rows();
    
        } while ($selectQuery->num_rows() > 0);
    $this->db->trans_complete();
    
    if ($this->db->trans_status()){
        die("[+] operation successfully completed.");
    }
    else{
        die("[-] operation encounted an error somewhere. not data was updated.");
    }
    

    }