简体   繁体   中英

Why will this password hash and compare not work?

The way I am hashing the password and inserting values into the database,

$q = $dbc -> prepare("INSERT INTO accounts (username, email, password, type, gender, joined)
                      VALUES (?, ?, ?, ?, ?, ?)");
$q -> execute(array($_POST['username'], $_POST['email'], 
                    hash('sha256', $_POST['password'] . date('y/m/d')), 
                    $_POST['type'], $_POST['gender'], date('y/m/d')));

When I compare then like this,

if ($count == 1 
&& $info['password'] === hash('sha256', $_POST['password'].$info['joined'])
&& $info['logcount'] != -1)

Both the hashes work but throw out different values? I am using the exact same formula for creating and comparing.

I am taking the user password, salting it with the current date, then hashing, both values are stored in the database and on comparison doing the exact same thing, all the tutorials online are all about hashing and creating secure hashes, not comparing.

Thanks

What type is joined ? If it's MySQL and you're using DATE, then it will print out as "YYYY-MM-DD". It's very likely that your salt differs. You may want to use a more foolproof way to salt the password.

Possible solutions:

  1. Make joined a string (VARCHAR in MySQL). That works, but is less efficient and won't allow you to easily sort/search by the date.

  2. Match the date precisely as your SQL implementation uses it. for MySQL, for example, use YYYY-MM-DD. Also, create the date string up front, don't call date('y/m/d') twice in your query. Create a variable up front with the date (like "2011-04-21"), use it for the salt, pass it into joined , and that should do.

  3. Use the UNIX_TIMESTAMP to turn the date into a number. No formatting necessary with that.

I'll guess the joined column in the database is a DATE or DATETIME column? If so, you're probably not getting the date back formatted as y/m/d , but Ymd or even Ymd H:i:s . You'll need to reformat it to get the same value.

If you're storing joined as something other than a varchar type, then the value you get from the database may not match the value returned from the date() function.

Either store joined as plain-text or use a value that you can extract both from the date() and the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM