php sha512 and javascript sha512 don't match - server side javascript?

504 views Asked by At

(full source code and database export attached below)

Hi, I'm working on a login script using PHP and JavaScript, and the SHA512 hashing algorithm, based on this tutorial: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL

I've found that when registering a new username, the PHP function which hashes the password on the server-side does not result in the same hash as when we check the password later client-side with JavaScript.

I've also put in some temporary debugging statements to provide more information about where the login failed. For example, at one point when we determine that the password entered doesn't match the password in the database, I've added:

    print("Password incorrect.");
    exit();

Here's the JavaScript sha512 code I'm using: github / emn178 / js-sha512 (Stack Exchange won't allow me to post another link with my current reputation)

Here are the relevant PHP code bits (in "register.inc.php"):

    $password = hash("sha512", $password);
    // Insert the new user into the database 
    if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password) VALUES (?, ?, ?)")) {
        $insert_stmt->bind_param('sss', $username, $email, $password);
        // Execute the prepared query.
        if (! $insert_stmt->execute()) {
            header('Location: ../error.php?err=Registration failure: INSERT');
        }
    }
    header('Location: ./register_success.php');

I can login successfully using the username and password provided in the example (and already pre-inserted in the database).

However, when I register a new username, then try to log in with that new user, I get "Password incorrect."

Doing some further debugging, I found that this is because the sha512.js code and the PHP hash() function are not giving me the same output when given the same input.

One solution that I've thought about, since I'm using that other "sha512.js" code, is to actually run server-side JavaScript (through node) and execute it from inside the PHP code.

I don't know how to pass an argument to the sha512.js from the command line. When I run "node sha512.js" from the terminal it executes correctly but I don't know how to supply the input or read the output in that context.

Any thoughts? There must be a better, established way to do this?

Thanks, Kip C.

zipped source code

0

There are 0 answers