Reputation: 27
I made a system that verifies users as they sign up, mail is sent to their email and when link in mail is clicked, account is activated. My problem is here that when login is attempted with the email and input password, it throws an error but when I copy the 10 characters random string hashed password into the password input, it gains access... MY QUESTION is "Please how can I make the input password to match with the hashed password ?"...... I tried to post the script here but I don't know how that is really done here
Thanks in Advance!
Upvotes: 2
Views: 188
Reputation: 2279
@vTp is referring to the old insecure method of doing MySQL queries but it opens up for a whole bag of SQL injections so please use prepared statements instead which is using auto-escaped typecasted variables for MySQL.
My suggestion:
# Database credentials
$mysqlsrv = "localhost";
$mysqlusr = "myusr";
$mysqlpsw = "mypsw";
$mysqldb = "mydb";
# Connect to database in the secure "prepared statement" way
$mysqli = new mysqli($mysqlsrv,$mysqlusr,$mysqlpsw,$mysqldb);
# Check for database connection errors
if(mysqli_connect_errno()) {
echo "Cannot connect to database";
exit();
}
# The user credentials (this could be from $_REQUEST or alike)
$username = "myuser";
$password = "123456";
# Encrypt the password
$password = sha1($password); # or whatever you are using - maybe md5
$query = "SELECT userId FROM users WHERE usr=? AND psw=?";
if($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("ss",$username,$password); # gets two strings as input. Use "i" for integer input instead of "s"
$stmt->execute();
$stmt->bind_result($userId);
# Check if the resultset from database is not empty
if($stmt->fetch()) {
echo "Found userID $userId";
} else {
echo "Could not find any users matching credentials";
}
$stmt->close();
}
You could also have MySQL encode the cleartext password - something like:
$query = "SELECT userId FROM users WHERE usr=? AND psw=SHA1(?)";
Another approach (if you use @vTp method) could be to fetch all username and encrypted passwords from the database (without selecting a WHERE
clause) and then check if there is a match in any of the returned rows. In this way you avoid SQL injections too but it is not the best approach (and only solves the problem for this specific query).
Upvotes: 2
Reputation: 776
You can choose a encryption method, say MD5,sha1 etc for saving user password in DB and encrypt the input password before login.
if you are using MySQL for saving user data. Then use a query like this,
SELECT * FROM users
WHERE email = '$email' AND password= MD5('$password')
Upvotes: 2
Reputation: 1317
You should use a reproducible hash function, like sha or md5 (less secure).
To check the user's inputted password with the hashed password you simply do
function isValid($password) {
return sha1($password) == $this->hashedPassword;
}
Bottom line: don't generate a random string as a password, unless you can reproduce it.
Upvotes: 1