Password hashing upon inserting a password to a database

Xp10d3 :

I'm confused on how the password hashing works. I don't understand the $salt thing and the PASSWORD_DEFAULT. I've read up on it a bit but still don't understand how it fits in my code. I only came here since it felt like my only option. Basically I have the passwords inserted into the database and have been told many times to hash the password (which I understand is reasonable) but I'm confused on how it works. I've seen that the way to do it is:

$hash = hash($password_variable . $idk_what_this_is);

I would understand that than I would insert the password into the database using:

$sql = "INSERT INTO dont (STR, USERNAME, PASSWORD, EMAIL) VALUES ('$key', '$username', '$hash', '$email')";

But I'm confused mostly on how it works, how getting the password changes, and what the second parameter is in the code since I am going to insert the data onto a database, than get that data and insert it back into a second database and than checking whether the user submitted that data.

sendemail.php

<?php
    /* Sends an email to the user and adds the special key to another database */
    $username = $_GET['username']; /* Gets the username that was submitted in the HTML form. */
    $password = $_GET['password']; /* Gets the password that was submitted in the HTML form. */
    $email = $_GET['email']; /* Gets the email that was submitted in the HTML form. */
    $servername = "localhost"; /* MySQL database. Change if needed! Most of the time its not localhost unless you're hosting on your computer. */
    $user = 'usernamelol'; /* MySQL username. Change if needed. */
    $pass = 'passwordlol'; /* MySQL password. Change if needed. */
    $dbname = 'vibemcform'; /* MySQL database name. Change if needed. */

    $bytes = random_bytes(10); /* Randomized code */
    $key = bin2hex($bytes); /* Makes the randomized code */

    $con = new mysqli($servername, $user, $pass, $dbname); /* Connects to the database */
    $query = mysqli_query($con, "SELECT * FROM `data` WHERE USERNAME='".$username."'"); /* Gets the username that was submitted */
    if (mysqli_num_rows($query) > 0) { /* If the username exists... */
            echo "ERROR: Username already exists. Please try again.";
            $con -> close();
            exit;
    } else { /* If the username DOESN'T exist... */
        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $pass);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO dont (STR, USERNAME, PASSWORD, EMAIL)
            VALUES ('$key', '$username', '$password', '$email')"; /* Insert all the data to the database */
            $conn->exec($sql);
        }
        catch(PDOException $e) {
            echo $sql . "<br>" . $e->getMessage();
        }
    }

    $conn = null;
    $msg = "localhost/vibemcform/verify.php?str=". $key . " Please verify your email!";
    $msg = wordwrap($msg,70);
    /*
    $headers = array("From: [email protected]",
        "X-Mailer: PHP/" . PHP_VERSION
    );
    */
    if (mail($email,"Verify your email",$msg/*, $headers*/)) {
        echo 'Message accepted! Check your email to verify your account. ';
    } else {
        echo 'Message not accepted. Contact the owner of the website! ';
    }
    echo 'Username submitted: ' . $username . ' Password submitted: ' . $password . ' Email submitted: ' . $email . ' .'; exit;
?>
Jay Blanchard :

A hash is a substitution of one thing for another thing in order to make the first thing hidden or undecipherable. You likely created your first hash, a two-way cipher, as a kid when you wrote the alphabet out and then wrote another line below your first with the alphabet being backward.

ABCDEFGHIJKLMNOPQRSTUVWXYZ
ZYXWVUTSRQPONMLKJIHGFEDCBA

'Z' is now 'A' and we can send coded messages to our friends and they can decode them! How clever are we?!?! We find out we're not clever at all when our little sister intercepts our coded notes and begins to translate them, foiling our plans for total tree-house domination. We need to find a way to modify our hash. How do we make the modification? We add salt!

A salt is some data used as an additional input to change our hash in order to make it more secure. We tell our friends to 'shift by 3' or maybe we include a number somewhere in the message which indicates the shift. Suddenly our hash is a little more complex:

ABCDEFGHIJKLMNOPQRSTUVWXYZ
CBAZYXWVUTSRQPONMLKJIHGFED

'C' is now 'A' with the whole backward alphabet shifted three characters. The goal of salts in the real world is to defend against things like dictionary and rainbow table attacks. password_hash() creates a random salt for each password.

Finally, there is the cost which refers to the algorithmic cost of performing the hash given the salt and the hash method. Since our friend Bobby was really good with the alphabet he was in charge of making the encrypted notes. If he did the encryption twice (shift and shift again) it doubled the cost of the hash, both in time and in effort. Three times would triple the cost and so on.

ABCDEFGHIJKLMNOPQRSTUVWXYZ
CBAZYXWVUTSRQPONMLKJIHGFED
FEDCBAZYXWVUTSRQPONMLKJIHG

'F' is now 'A'. It's much more secure but it may not have been worth it if the message took too long to generate and too long to decipher. For our computers and servers, the cost is much more complex but in many cases, we have the option of setting a value which relates to a factor of the cost. It takes some fine-tuning to get the balance, speed vs. effort, correct and is best left to the experts.

PHP's password_hash() function doesn't perform a two-way cipher though, it is one-way only. You cannot reverse engineer the hash to figure out the password, unlike our attempts at secrecy above.

If you use the default options for the password_hash() function PHP will generate a random salt for each password as it is hashed. The random salt is an additional layer of security which makes it exceptionally hard to crack any passwords. Even if two or more users use the same password each of their hashes will be different.

The first person we register is Adam West, Batman from the 1960's television series. He wants the username "bwayne" and his password is "I'm Batman!" (notice the password is a phrase and includes spaces, far better than any standard password you may have used in the past.). The entry, if there is nothing wrong with our script, goes in smoothly.

The next person who registers is Michael Keaton, Batman from the 1989 movie. He uses a different username, but his password is exactly the same.

I'm Batman!

Here is where the random salt provided by PHP comes in so handy. Even though the passwords are the same each hash is completely different.

enter image description here

Because of the type of encryption involved the first few characters of the password match but everything beyond those characters is different and unique. These few characters indicate to password_verify() which algorithm was used for the hashing. This algorithm is specified as the second parameter of password_hash(). This answers $idk_what_this_is

$hash = hash($password_variable . $idk_what_this_is);

NOTE: We don't want to get into the finer points of who Batman really is but we did have them both go back and change their passwords once testing was complete. No one needs to know the location of the Batcave but us.....um, er.....them.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27825&siteId=1