Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am having an issue getting the password being stored on in mysql to match the Login password using salt.

Here is the code from my password creation:

        $hash = hash('sha256', $password);

        function createSalt()
        {
        $text = md5(uniqid(rand(), true));
            return substr($text, 0, 3);
        }

        $salt = createSalt();
        $password = hash('sha256', $salt . $hash);

Here is the code in my login page:

        $userData = $result->fetch_array(MYSQL_ASSOC);

        $hash = hash('sha256', $password);

        $password = hash('sha256', $userData['salt'] . $hash);

        //$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) ); 

        if($password != $userData['Password']) // Incorrect password. So, redirect to login_form again.

There are no errors creating the password in mysql (the field is populated with i.e 0d02a88c1e1057a64df6b3fed4c6ad64e228313b803e9f9b36...

While the Login creates something like: 51839f9a15dac1f26825f4cd5d2ecf7ae83ea88d440415b04fb6ae41c3a0566f

Just not sure where the issue is. Thanks in advance, I am very new to PHP.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
184 views
Welcome To Ask or Share your Answers For Others

1 Answer

First, you have some confusing variable naming here - you use $password to represent both the plaintext password and the salt-and-hashed representation. That makes it harder to read your code.

Second, let's look at your code as a series of states to find where they might be going wrong:

  1. Password entry. Is the same string being passed in both cases? Have you paid attention to whitespace and capitalization? Use a debugger to verify. If the plaintext password is not byte-for-byte identical, the initial sha256 hash should show differences at this point.
  2. Salt generation/retrieval. Did you save/retrieve the exact same salt, byte-for-byte? Again, watch for whitespace/capitalization and also check that your database isn't silently truncating or changing the encoding for the string.
  3. Compare the strings after they have been concatenated but before the second sha256 hash operation. By definition, since the final output is different, either your plaintext password or salt is not byte-for-byte identical. This will help you tell if one or both are the culprits.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...