1

Below is a simple registration script using php, I obviously want to store peoples data securely. I was wondering where would be the best place to implement the hashing script? Would it be implemented in the script below or have it alone?

<?php
    //values to be inserted in database table
    //session_start();
    include('connect.php');
    $email = $_POST['email'];
    $password= $_POST['password'];
    $username= $_POST['username'];

    $query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
    $statement = $mysqli->prepare($query);

    //bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
    $statement->bind_param('sss', $username, $email, $password);

    if($statement->execute()){
         print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />'; 
    }else{
         die('Error : ('. $mysqli->errno .') '. $mysqli->error);
    }
    $statement->close();
    ?>

Another thing, when fetching peoples information from the database so they can sign in do I fetch their hashed password or do I have to recreate a hashed version of the password they've entered? I've read different ways of doing it, I just want to know the most secure. Thank you

EDIT:

This is my login code

<?php
include 'connect.php';
if ( !isset($_POST['username'], $_POST['password']) ) {
    // Could not get the data that should have been sent.
    die ('Username and/or password does not exist!');
}
// Prepare our SQL 
if ($stmt = $mysqli->prepare('SELECT password FROM users WHERE username = ?')) {
    // Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute(); 
    $stmt->store_result(); 
    // Store the result so we can check if the account exists in the database.
    if ($stmt->num_rows > 0) {
        $stmt->bind_result($password);
        $stmt->fetch();      
        // Account exists, now we verify the password.
        if (password_verify($_POST['password'], $password)) {
            // Verification success! User has loggedin!
                        echo 'You have logged in!';
        } else {
            echo 'Incorrect username and/or password!';
        }
    } else {
        echo 'Incorrect username blar password!';
    }
    $stmt->close();
} else {
    echo 'Could not prepare statement!';
}
?>

ANSWER:

<?php
//values to be inserted in database table
//session_start();
include('connect.php');

//Fixed cost of 10 to fit server req
//Random salt to be added to the pass
$options = [
    'cost' => 10,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];

$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];

$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);

//bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
$statement->bind_param('sss', $username, $email, $password);

if($statement->execute()){
     print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />'; 
}else{
     die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
Small Legend
  • 733
  • 1
  • 6
  • 20
  • hashed sir, when would you ever want to store plain text passwords? – Small Legend Sep 23 '15 at 11:26
  • 1
    [password_hash()](http://www.php.net/manual/en/function.password-hash.php)/[password_verify()](http://www.php.net/manual/en/function.password-verify.php) – Mark Baker Sep 23 '15 at 11:30
  • 1
    http://www.phptherightway.com/#password_hashing – Mark Baker Sep 23 '15 at 11:34
  • @MarkBaker could you have a look at my edit, thank you – Small Legend Sep 23 '15 at 13:14
  • @MarkBaker Also may I add, the pass‌​word_verify() link you sent me is very limited and doesn't consider the use of salts – Small Legend Sep 23 '15 at 13:32
  • password_verify() doesn't require you to pass in a salt.... it's part of the stored hash, you pass in that stored hash with the entered password, and the internals of password_verify() handle checking with the salted value.... and personally I'd use default values for the options and algorithms arguments of password_hash() - though admittedly I've upped my cost option to 17 – Mark Baker Sep 23 '15 at 13:58

1 Answers1

-1

While putting Users value into the variable is the perfect time to sanitize It would be great if you use a Global function to sanitize data and use that function everywhere

Here is an Example of secure code (without OOP ):

<?php

    // create a globa function
    // 
    function string_sanitize($value) {

        $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
        $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");

        return str_replace($search, $replace, $value);

    }

    function sanitize($value){

        return $this->string_sanitize(htmlentities(trim($value)));

    }

    //values to be inserted in database table
    //session_start();
    include('connect.php');
    $email = sanitize($_POST['email']);
   $username = sanitize($_POST['username']);

   // Sanitize password using hash()
   $password = hash('sha256', $_POST['password']);

    $query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
    $statement = $mysqli->prepare($query);

    //bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
    $statement->bind_param('sss', $username, $email, $password);


    if($statement->execute()){
         print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />'; 
    }else{
         die('Error : ('. $mysqli->errno .') '. $mysqli->error);
    }
    $statement->close();


    ?>
Aniruddha Chakraborty
  • 1,849
  • 1
  • 20
  • 32
  • 1
    Why would you sanitize a hash that you've generated yourself? You know exactly what the value contains, none of it HTML or any of the special characters that you're trying to avoid – Mark Baker Sep 23 '15 at 11:32
  • This is new, I've not read anything about string sanitizing. How would perform the login step with the sanitized strings? would I sanitize the users entered password and then check whether the sanitized version is in the database? ( i'll edit my login code to the post ) – Small Legend Sep 23 '15 at 11:34
  • 1
    You shouldn't need to sanitize passwords: doing so actually reduces entropy making them less secure - read http://www.phptherightway.com/#security to understand the difference between escaping, sanitizing, and validating, and about how to secure passwords – Mark Baker Sep 23 '15 at 11:36
  • Ok .. I'm editing the code .. sorry for my mistake – Aniruddha Chakraborty Sep 23 '15 at 11:37
  • May I ask, why do you use this method instead of standard md5? – Small Legend Sep 23 '15 at 11:37
  • Md5 Sucks! using md5 in year of 2015 is not good because as far as i know .. md5 is not secure enough now :) – Aniruddha Chakraborty Sep 23 '15 at 11:39
  • as @MarkBaker said , Md5 is old, easily breakable hash .. – Aniruddha Chakraborty Sep 23 '15 at 11:42
  • Okay, well what advice would you give me @MarkBaker – Small Legend Sep 23 '15 at 11:42
  • 1
    @SmallLegend - Read my comments - password_hash()/password_verify() and read http://www.phptherightway.com/#security – Mark Baker Sep 23 '15 at 11:43
  • @MarkBaker thank you, only been writing PHP for a week, quite a bit to take in – Small Legend Sep 23 '15 at 11:47
  • 1
    There's been a lot of bad PHP tutorials written over a great many years that are still floating out there on the interwebs.... that's why [PHP - The Right Way](http://www.phptherightway.com/) was created, to provide all the best advice on writing PHP in one place, and to keep it up-yto-date with best practise..... bookmark it, along with the PHP docs, and refere to them frequently – Mark Baker Sep 23 '15 at 11:49
  • @MarkBaker brilliant, thanks a lot for your help – Small Legend Sep 23 '15 at 11:54
  • A global sanitizing function is a really bad approach. – Pekka Sep 23 '15 at 12:00
  • What you would prefer where you are not using OOP ? @Pekka웃 – Aniruddha Chakraborty Sep 23 '15 at 12:02
  • See http://stackoverflow.com/questions/4223980 – Pekka Sep 23 '15 at 12:02