i use crypt() function for protect password when i create user in database, but when i try to make a authentification system for connect my user, i don't understand how is work.
With this code, this always pass into the if "WRONG ID OR PASSWORD" :
<?php
//connexion to database
include'connexionBDD.php';
// Check connection
if ($bdd->connect_error) {
die("Connection failed: " . $bdd->connect_error);
}
echo "Connected successfully (".$bdd->host_info.")";
$pseudonyme = $_POST['pseudo'];
$password= $_POST['mdp'];
//on crypte le mot de passe
$password= crypt($password);
$req = $bdd->prepare('SELECT ID_utilisateur FROM utilisateurs
WHERE Pseudonyme = :pseudo AND Mot_de_passe = :mdp');
$req->execute(array(
'pseudo' => $pseudonyme,
'mdp' => $password));
$result= $req->fetch();
if(!$result)
{
echo "WRONG ID OR PASSWORD";
}
else
{
session_start();
$_SESSION['ID_utilisateur'] = $resultat['ID_utilisateur'];
$_SESSION['Pseudonyme'] = $pseudonyme;
$pseudo = $_SESSION['Pseudonyme'];
echo "<p> You are connected with $pseudo !<p></div>";
}
?>
crypt() as of now is not preferred way to store passwords.
Use password_hash() to generate password and password_verify() to compare them.
Example code:
$password = "tere";
$cryptPassword = password_hash($password, PASSWORD_DEFAULT);
$verify = password_verify($password, $cryptPassword);
var_dump($verify); // Returns bool(true)
Also crypt() is well documented in PHP Manual, read about that.
Related
my login activity cannot read encrypted Password i tried without encrypted password and it works and im not sure if the error from php or activity itself of how to decryption password
im Using PASSWORD_BCRYPT
<?php
include "conn.php";
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$sql_login = "SELECT * FROM users WHERE Email = :EMAIL and Password =:PASSWORD";
$stmt = $PDO->prepare($sql_login);
$stmt->bindParam(':EMAIL', $Email);
$stmt->bindParam(':PASSWORD', $Password);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$returnApp = array('LOGIN' => 'SUCCESS');
echo json_encode($returnApp);
}else{
$returnApp = array( 'LOGIN' => 'FAILED');
echo json_encode($returnApp);
}
?>
To correctly use hashing of a password in PHP, use the password_hash and password_verify combination.
When a user signs up, you get his password, hash it and store it in the database:
$hash = password_hash($_POST['newpassword'], PASSWORD_DEFAULT);
// store $hash in database column "password"
When this user wants to login, you check against the hash:
// fetch hash from database, store it in $stored_hash
$logged_in = password_verify($_POST['password'], $stored_hash);
if ($logged_in === TRUE) {
echo "Welcome!";
} else {
echo "Username or password incorrect.";
}
Final notes:
Use PASSWORD_DEFAULT and make sure your database can store the result (also in the future). Hashing algorithms happen to get cracked once in a while.
You could use another provider like Google or Facebook to handle your authentication. This does have its drawbacks as well though.
I write the following loginCheck code and the database schema I use is as follows:
userinfo:
username varchar
password varchar
code:
<?php
//set the MIME type to application/json
//header("Content-Type: application/json");
//get the username and password
$username = $_POST['username'];
$password = $_POST['password'];
//require database operation
require 'database.php';
$stmt = $mysqli->prepare ("SELECT username, password, COUNT(*) FROM userinfo WHERE username=?");
if(!$stmt){
echo json_encode(array(
"success" => false,
"message" => "an error occured, please try again"
));
exit;
}
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($returnedUsername, $hashedPassword, $count);
$stmt->fetch();
if ($count==1 && crypt($password, $hashedPassword) == $hashedPassword) {
//all information provided is correct, start a session
ini_set("session.cookie_httponly", 1);
session_start();
$previous_ua = #$_SESSION['useragent'];
$current_ua = $_SERVER['HTTP_USER_AGENT'];
$_SESSION['username'] = $username;
if(isset($_SESSION['useragent']) && $previous_ua !== $current_ua){
die("Session hijack detected");
} else{
$_SESSION['useragent'] = $current_ua;
}
//create a token
$_SESSION['token'] = substr(md5(rand()), 0, 10);
echo json_encode(array(
"success" => true,
"token" => htmlentities($_SESSION['token']),
"username" => htmlentities($_SESSION['username'])
));
exit;
} else {
echo json_encode(array(
"success" => false,
"message" => "Incorrect Username or Password"
));
exit;
}
$stmt->close();
?>
The url is:
http://ec2-54-148-227-9.us-west-2.compute.amazonaws.com/~beibeixhb/Calendar/calendar.php
I am not sure why it prevent me from logging in, any suggestions?
You are using the hashed version of your password as a salt to the password entered and you expect that to be the same as the hashed password. I don't think this can ever happen.
crypt($password, $hashedPassword) == $hashedPassword
It's not clear from your code where you get the salt from, but if you didn't use salt to hash the password to start with, taking out that second argument of crypt should do the job for you.
Alternatively, use the right salt as a second argument to crypt.
php.net script: http://php.net/manual/en/function.password-hash.php
and: http://php.net/manual/en/function.password-verify.php
The apparent simplicity of this password verification routine is very appealing, but after a day of reading at stackoverflow and innumerable hacks, here is my very simple, not-at-all-secure, testing version:
<?php
$p = "bumblebee";
$hash = (password_hash($p, PASSWORD_DEFAULT));
echo ($p);
echo ($hash);
if (password_verify('bumblebee', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
ABOVE RETURNS 'Password is valid!' (this is two scripts from PHP.net combined)
BELOW DOES NOT WORK (only diff is the hash is written to DB and read back, then converted to a string)
<?php
$userName = $_REQUEST["userName"];
$passWord = $_REQUEST["passWord"];
// $p = "$passWord";
// $hash = (password_hash($p, PASSWORD_DEFAULT));
//set DB access variables
require_once('./php/hs_DBlogin.php');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$passWord_get = mysqli_query($conn, "SELECT passWordHash FROM hsUser WHERE userName='$userName' LIMIT 1");
$passWord_out = mysqli_fetch_array($passWord_get);
$hashAsStr = $passWord_out[0];
echo ($hashAsStr);
echo ($_REQUEST["passWord"]);
if (password_verify($_REQUEST["passWord"], $hashAsStr)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
Here is the insert to DB script:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$passWordHash = password_hash('$passWord', PASSWORD_DEFAULT);
$sql = "INSERT INTO `hsUser`(`firstName`, `lastName`, `userName`, `passWordHash`,`hsStatus`) VALUES ('$firstName','$lastName','$userName','$passWordHash','$hsStatus')";
Gave up on php's password_verify and used sha1
script at:
http://www.localwisdom.com/blog/2013/03/building-a-simple-registerlogin-system-in-php-using-sha256/
after some clean-up, works fine
Please don't give up so fast, your alternative method using SHA256 is an extremely unsafe method to store your user's passwords.
As others already mentioned, it is recommended to use a varchar(255) field. According to your comments this is not the problem though.
If the code you are showing for the registration is exactly your working code, then the culprit is very likely this line:
$passWordHash = password_hash('$passWord', PASSWORD_DEFAULT);
This statement will create a hash of the text '$passWord' and not from the variable $passWord, so instead it should be:
$passWordHash = password_hash($passWord, PASSWORD_DEFAULT);
This is my first attempt in securely storing passwords and I would like to make sure that everything is done correctly. I was advised to use SHA-256 hashing alongside salt.
Assuming user submitted their password thorough form, we get the password via
$password = $_POST["password"];
What is correct way to salt $password and use SHA-256 hashing on it, so it can than be stored in a password field "password CHAR(64)" in a database?
Once done and stored how would I than compare value stored in a database to one user entered in a login form? Lets assume $loginPassword = $_POST["loginPassword"]; is what user entered.
Instead of using SHA family methods, you can use the crypt() function to salt it for you.
Here is an example script (save and login) using PDO.
Save password in DB
<?php
// Set the password
$password = 'mypassword';
// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
echo $hash; // for testing purposes only
$mysql_username = 'username'; // for DB
$mysql_password = 'password'; // for DB
$dbh = new PDO('mysql:host=localhost;dbname=database_name', $mysql_username, $mysql_password);
$stmt = $dbh->prepare("INSERT INTO table_name (name,pass) VALUES (:name,:pass)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':pass', $pass);
// insert rows
// $name = $_POST['name'];
// $name = $_POST['pass'];
$name = "username";
$pass = $hash;
$stmt->execute();
Login script
<?php
$mysql_username = 'username'; // for DB
$mysql_password = 'password'; // for DB
$dbh = new PDO('mysql:host=localhost;dbname=database_name', $mysql_username, $mysql_password);
/*
$username = $_POST['username'];
$password = $_POST['password'];
*/
$username = "username";
$password = "mypassword";
$sql = "SELECT * FROM table_name WHERE name=:username";
$statement = $dbh->prepare($sql);
$statement->bindValue(':username',$username,PDO::PARAM_STR);
if($statement->execute())
{
if($statement->rowCount() == 1)
{
$row = $statement->fetch(PDO::FETCH_ASSOC);
if (crypt($password, $row['pass']) === $row['pass'])
{
$username = $row['name'];
$email = $row['email'];
echo "Stage 1";
echo "<hr noshade size=\"1\">";
echo "Hello " .$username;
exit;
}
else
{
// include "error_login.php";
echo "Stage 2 - ERROR";
}
}
else
{
// include "error_login.php";
echo "Stage 3 error";
}
}
If you're on PHP 5.5 or later, there's the built-in password_hash() and password_verify() with Bcrypt - if you're on PHP 5.3.7 or later, there's the password_compat compatibility library; all this is per the PHP.net Safe Password Hashing FAQ entry.
Essentially, on PHP 5.3.7 and above, replace the old crypt() with password_hash() and password_verify().
See my answer to PHP Secure password generation and storage for some more details on cost choice, but it boils down to the very simple:
<?php
/**
* In this case, we want to increase the default cost for BCRYPT to 12.
* Note that we also switched to BCRYPT, which will always be 60 characters.
*/
$options = [
'cost' => 12,
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."\n";
?>
to generate the hash, then you store the output string, and then verify with:
<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
Both examples come from the PHP.net Password Hashing page.
I've made encrypting of the password in my register script and they are stored in the database, and I have to use them to login, so I would want to use the unencrypted ones to login. I've read some of the threads in here but nothing is helping me. How can I add it in my login.php? The salt is also stored in the database.
This is my register.php script for encrypting
$hash = hash('sha256', $password1);
function createSalt()
{
$text = md5(uniqid(rand(), TRUE));
return substr($text, 0, 3);
}
$salt = createSalt();
$password = hash('sha256', $salt . $hash);
and this is my login.php with season
//Create query
$qry="SELECT * FROM member WHERE username='$username' AND password='$password'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
$_SESSION['SESS_FIRST_NAME'] = $member['username'];
$_SESSION['SESS_LAST_NAME'] = $member['password'];
session_write_close();
header("location: profile.php");
exit();
}
else {
//Login failed
//error message
}
else {
die("Query failed");
}
These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.
Read the php documentation to find out about the possibilities and best practices:
http://www.php.net/manual/en/function.password-hash.php
Save a password hash:
$options = [
'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];
$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);
// Now insert it (with login or whatever) into your database, use mysqli or pdo!
Get the password hash:
// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;
if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
According to php.net the Salt option has been deprecated as of PHP 7.0.0, so you should use the salt that is generated by default and is far more simpler
Example for store the password:
$hashPassword = password_hash("password", PASSWORD_BCRYPT);
Example to verify the password:
$passwordCorrect = password_verify("password", $hashPassword);
array hash_algos(void)
echo hash('sha384', 'Message to be hashed'.'salt');
Here is a link to reference http://php.net/manual/en/function.hash.php
You couldn't login because you did't get proper solt text at login time.
There are two options, first is define static salt, second is if you want create dynamic salt than you have to store the salt somewhere (means in database) with associate with user.
Than you concatenate user solt+password_hash string now with this you fire query with username in your database table.
I think #Flo254 chained $salt to $password1and stored them to $hashed variable. $hashed variable goes inside INSERT query with $salt.
You can't do that because you can not know the salt at a precise time. Below, a code who works in theory (not tested for the syntaxe)
<?php
$password1 = $_POST['password'];
$salt = 'hello_1m_#_SaLT';
$hashed = hash('sha256', $password1 . $salt);
?>
When you insert :
$qry="INSERT INTO member VALUES('$username', '$hashed')";
And for retrieving user :
$qry="SELECT * FROM member WHERE username='$username' AND password='$hashed'";