sql >> Base de Datos >  >> RDS >> Mysql

Actualice todas las filas en la base de datos con un valor hash

Primero, debo decir que si tiene datos no confidenciales en una base de datos, las funciones integradas de mysql pueden brindarle resultados de hash directamente con declaraciones de actualización usando solo mysql.

Esta respuesta no se trata de eso. Se trata de datos confidenciales, como contraseñas.

Te di un enlace a PHP password_hash() y password_verify() ejemplo.

Aquí está Ese enlace otra vez. Ese enlace a la izquierda es para PDO. El siguiente Enlace aquí mismo es similar y para mysqli.

En el enlace PDO mira la línea

$hp=password_hash($ctPassword,PASSWORD_DEFAULT); // hashed password, using 

Entonces, digamos que ahora tiene una columna con texto sin cifrar llamada ctPassword . alter table y agregue una nueva columna para algo como hashedPassword . Siga el enlace que proporcioné, modifique en consecuencia, haga un hash de los valores de ctPassword en hashedPassword con una declaración de actualización.

Luego pruébalo a fondo. Cuando todo esté bien en el mundo, suelta la ctPassword columna y no volver a utilizarla nunca más. Para ser claro , nunca almacene contraseñas de texto claro en bases de datos. Almacene valores hash unidireccionales y verifíquelos. Los enlaces anteriores muestran cómo.

Editar

Aquí es completamente de PHP desde donde creo que esto debe ser impulsado, a diferencia de las funciones hash de mysql, qué asco. Después de todo, está utilizando PHP, y es allí donde brillará su hash y verificación robustos. Las mejores prácticas en mi opinión, mientras que la gente de mysql no gasta exactamente el ancho de banda mental en eso. Estoy a favor de hacer todo lo posible en mysql. Pero nunca este tema, usando hashes. Deje que PHP maneje este.

Esquema

create table sometable
(   id int auto_increment primary key,
    userName varchar(40) not null,
    ctPassword varchar(40) not null -- clear text password (means humans can read it, basically)
    -- note, not a great definition of ct but it implies it has not been hashed for safety
);

insert sometable(userName,ctPassword) values
('Brenda','I watch TV too much'),
('Drew','PatriotsWorldChamps'),
('stealth_guy','JFIDU&JF_Anchovies');

A lo largo viene la idea, hey, quiero hachís seguros ahora. Podría ser hackeado.

-- http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
alter table sometable add column hashedPassword varchar(255);
-- now I have 4 columns, hashedPassword is currently nullable
show create table sometable; -- confirms this fact

PHP para recorrer y actualizar una nueva columna destinada a limpiar antes de no tener un concepto hash (que creo que todos hemos visto 1 millón de veces en la pila)

PHP para parchear:

<?php
    // turn on error reporting, or wonder why nothing is happening at times
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    //mysqli_report(MYSQLI_REPORT_ALL);
    error_reporting(E_ALL);
    ini_set("display_errors", 1);    // Begin Vault

    // credentials from a secure Vault, not hard-coded
    $servername="localhost";
    $dbname="login_system";
    $username="dbUserName";
    $password="dbPassword";
    // End Vault

    try {
        $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $stmt = $db->prepare("select id,ctPassword from sometable");
        $stmt->execute();
        $stmt->bindColumn('id', $theId);        // bind the results into vars by col names
        $stmt->bindColumn('ctPassword', $cPassword);        // ditto

        // http://php.net/manual/en/pdostatement.fetch.php
        while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
            // as we loop thru here, the $theId and $cPassword variables will be auto-magically updated
            // for us because they have been bound as seen above
            $hPassword=password_hash($cPassword,PASSWORD_DEFAULT); // we now have a hashed password based on orig clear text one
            echo $cPassword . "   " . $hPassword . "<br>";
            // each time you run this with same data the hashes will be different due to changes in the salt
            // based on above PASSWORD_DEFAULT (look at manual page for password_hash)
            $sqlUpdate="UPDATE sometable set `hashedPassword`='$hPassword' where `id`=$theId";

            $db->query($sqlUpdate);
        }
        // .. other cleanup as necessary
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
        exit();
    }
?>

Ejecute el script php, verifique los resultados. Esos son míos, tuyos will diferir de. El tuyo incluso será diferente del tuyo si lo vuelves a ejecutar. Motivo mencionado en el código.

select * from sometable;

+----+-------------+---------------------+--------------------------------------------------------------+
| id | userName    | ctPassword          | hashedPassword                                               |
+----+-------------+---------------------+--------------------------------------------------------------+
|  1 | Brenda      | I watch TV too much | $2y$10$pJ5maui2OlrIPAtISf4u2OqeqEXU9ycDpCNNpp6xDh1uzIv/6ybuW |
|  2 | Drew        | PatriotsWorldChamps | $2y$10$kHAKRSeHLi9cghPKTKox/.kXiFgq6ELWwExGcVvbf1yYprtTvi.Ba |
|  3 | stealth_guy | JFIDU&JF_Anchovies  | $2y$10$HOkBAkP7ZVIZ7NQB50aKAuhG5WjLHU9AtJCiY2E6h/M2YZuxc2l5K |
+----+-------------+---------------------+--------------------------------------------------------------+