Search code examples
phphashpassword-protection

Should I add salt from a custom randomly generated method to my hashed password? PHP


I am creating a log in system with database and wanted to ask about hashing passwords. I currently use the function password_hash() in PHP and in addition I add a custom random string of 20 characters. Looks something like this:

 $salt = generateRandomString();
 $hashedPwd = password_hash($pwd + $salt, PASSWORD_DEFAULT);

And the function:

function generateRandomString($length = 20) {
   $characters='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+{}|[]/?~`';
   $charactersLength = strlen($characters);
   $randomString = '';
   for ($i = 0; $i < $length; $i++) {
       $randomString .= $characters[rand(0, $charactersLength - 1)];
   }
   return $randomString;

I also later send the random string to the database and verify it together with the password when logging in.

My question is whether I need the extra string? Keep in mind that I want this to be as secure as possible.


Solution

  • Firstly, don't generate a random string and including it during the hashing / storage process.

    It will fail with password_verify() during verification, since it won't have any idea as to what the added salt was since it's not part of its core process.

    My question is whether I need the extra string?

    A: No and I already said this above.

    Why? First it won't work, and it's not needed.

    password_hash() generates its own.

    If you really want to add your own salt to it, then drop the method you're using that adds to the hash. It's listed in the manual.

    You should be careful though, as, and I quote:

    "Warning The salt option has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default."

    Note: You should heed the warnings that are also in the manual's Notes:

    Caution

    It is strongly recommended that you do not generate your own salt for this function. It will create a secure salt automatically for you if you do not specify one.

    As noted above, providing the salt option in PHP 7.0 will generate a deprecation warning. Support for providing a salt manually may be removed in a future PHP release.

    Since you appear to be new at this; if you're not already using a prepared statement to store and retrieve data, then I highly suggest you look into using them.

    It will help against an possible SQL injection.


    Keep in mind that I want this to be as secure as possible.

    There is something you can use which was introduced in PHP 7.2.0, and that is Argon2.

    For more information on this, consult the following:

    It doesn't get as secure as that.