Secure two way hashing technique

197 views Asked by At

I am currently developing a Document Authentication System and I want the Passwords of the users to be hashed or encrypted ..

So my question is, what is the best and most secure TWO WAY Hashing or Encrypting method I will use ..

1

There are 1 answers

6
Masivuye Cokile On

As it has been suggested in the comments above the best and easy way is to use password_hash(); and password_verify(); more info is available in the php.net website, and also make use of prepared statements either with mysqli or pdo in my basic user registration i made use of PDO.

Please not this is just a basic example of how to use password_hash and password_verify();

we will use the password_hash() upon registration and password_verify() upon login

db.php

<?php


    $server="localhost";
    $username="root";
    $password="";

    try{

        $dbh = new PDO("mysql:host=$server;dbname=sytemDb",$username,$password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }catch(PDOException $exc){

        error_log($exc);
    }
?>

The above script makes connection to our database.

register.php

<?php

    include 'db.php';
    $errors="";
    if (isset($_POST['register'])) {

        //check if values are not empty

        if(empty($_POST['email'])){

            die("please enter email");
            $errors++;
        }else{

            $email = $_POST['email'];

            //then check for valid email
        }
    }
    if(empty($_POST['upass'])){

        die("enter password");
        $errors++;
    }else{

        $password = $_POST['upass'];

        $hash = password_hash($password,PASSWORD_DEFAULT);//hashing password
    }

    if($errors <=0){

        //no errors save to db

        $stmt= $dbh->prepare("INSERT INTO users (username,password) VALUES(?,?)");
        $stmt->execute(array($username,$hash));

        echo "User registered";
    }


?>







<!DOCTYPE html>
<html>
<head>
    <title>User Registration</title>
</head>
<body>


    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

        <input type="email" name="email" placeholder="Ente Username">
        <input type="password" name="upass" placeholder="Enter Password">
        <button type="submit" name="register">Register</button>

    </form>

</body>
</html>

Login.php

<?php
    ob_start();
    session_start();

    include 'db.php';

    if(isset($_POST['login'])){


        if(empty($_POST['username']) || empty($_POST['pass'])){

            die("enter password or username");
        }else{

            $uname = $_POST['username'];
            $password = $_POST['pass'];
        }

        try {

            $stmt = $dbh->prepare("SELECT userid,password,username from users where username = ?");
            $stmt->bindValue(1,$uname);
            $stmt->execute();

            $results = $stmt->fetchall(PDO::FETCH_ASSOC);

            if(count($results) > 0){
                //if username is correct continue check entered password against saved hash

                foreach ($results as $row) {

                    if(password_verify($password,$row['password'])){
                        //password and saved hash match go to dashboard

                        echo "login success";
                        $_SESSION['user']= $row['userid'];
                        header("refresh:5;url=dashboard");
                    }else{

                        echo "username and password does not match";
                    }
                }
            }else{

                echo "username and password does not match";
            }

        } catch (PDOException $e) {


            error_log($e);

        }
    }






?>




<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>

<form method="POST" action="">

    <input type="text" name="username" placeholder="Enter username">
    <input type="password" name="pass" placeholder="Enter password">

    <button type="submit" name="login">Login</button>

</form>

</body>
</html>

This should do its very basic password hash is available in the manual here and here

password_verify() also available here

Please make use of php 5.6 or above of which u were supposed to already do.

That's about it. Hope this will point you to the correct direction.

NB: Always verify input from the user, don't forget to filter and sanitize the input then prepare a statement to save to the db.

incase a user forget a password, well there are many ways to reset the user password, one basic way is to have an autho token column on ur db.

The following way is very basic for beginners just to kickoff your career lol ;)

<?php

function ForgetPassword()
{

    try {
        //search the user on the database
        $stmt = $dbh->prepare("SELECT email,userid,firstname,lastname from users where email = ?");
        $stmt->bindvalue($email);
        $stmt->execute();
        $results = $stmt->fetchall(PDO::FETCH_ASSOC);
        if (count($results) > 0) { //user found generate authentication token
            foreach ($results as $row):
                $userid     = base64_encode($row['userID']);
                $randomAuth = md5(uniqid(rand()));
                $dataUpdate = $dbh->prepare("UPDATE users set auth_token = ? where email = ?");
                $dataUpdate->execute(array(
                    $randomAuth,
                    $row['email']
                ));

                //send reset link to the user

                $link = "<a href=\"" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] . "resetpassword?id=$userid&token=$randomAuth\">Reset your password</a>";

                $header = "MIME-Version: 1.0" . "\r\n";
                $header .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                $header .= 'From: <>' . "\r\n";

                $message = "<p> Hello " . $row['firstname'] . " " . $row['lastname'] . "</p>";
                $message .= "<p> You have requested to reset your password your password</p>";
                $message .= "<p>" . $link . "</p>";

                if (mail(($row['email']), "Password Reset", $message, $header)) {

                    $successMessage = "Reset link sent to the provided email address";

                } else {

                    error_log("cound not send message");
                }
            endforeach;
        } else {

            $successMessage = "Reset link sent to the provided email address";
        }
    }
    catch (PDOException $ex) {

        error_log($ex);
    }

}
?> 

Then reset passwordpage

<?php

function resetPassword()
{

    if (isset($_GET['code']) && isset($_GET['token'])) {

        $code  = base64_decode($_GET['code']);
        $token = $_GET['token'];

        if (isset($_POST['resetpassword'])) {

            //check empty fields

            if (empty($_POST['newpassword'])) {

                $errorMessage = "enter password";
                $errors++;
                return $errorMessage;
            } else {

                $password = $_POST['newpassword'];

                $hash = password_hash($password, PASSWORD_DEFAULT); //password encryption
            }
            if (!empty($_POST['newpassword']) && empty($_POST['confirmpassword'])) {

                $errorMessage = "Please confirm your password";
                $errors++;
                return $errorMessage();
            }

            if (!empty($_POST['confirmpassword']) && $_POST['confirmpassword'] !== $_POST['newpassword']) {

                return "Passwords does not match";
                $errors++;
            }

        }

        if ($errors <= 0) {

            try {

                $stmt = $dbh->prepare("Update users set password = ? where userID = ? AND auth_token = ?");
                $stmt->execute(array(
                    $hash,
                    $code,
                    $token
                ));

                return "Password successfully changed.. Redirecting to login page";

                $update = $dbh->prepare("UPDATE users set aut_token = NULL where userID = ? ");
                $update->bindValue(1, $code);
                $update->execute();

                header("refresh=3:url;login");

            }
            catch (PDOException $e) {

                error_log($e->getMessage());
            }

        }

    } else {
        //token code error
        return "The link have expired, please go back and request a new one";

    }


}
?>