Code on my register page:
$p_salt = rand_string(20);
$site_salt="subinsblogsalt"; /*Common Salt used for password storing on site.*/
$salted_hash = hash('sha256', $password.$site_salt.$p_salt);
I then insert the salt in to the database, along with the salted passwords, but when I do it on my login page:
if(isset($_POST) && $email!='' && $password!=''){
$sql=$dbh->prepare("SELECT id,password,psalt FROM user WHERE email='".$email."'");
$sql->execute(array($email));
while($r=$sql->fetch()){
$p=$r['password'];
$p_salt=$r['psalt'];
$id=$r['id'];
}
$site_salt="subinsblogsalt";/*Common Salt used for password storing on site. You can't change it. If you want to change it, change it when you register a user.*/
$salted_hash = hash('sha256', $password.$site_salt.$p_salt);
But they don't match at all, I echoed the salted hash to compare it to the one in the database but they're different.
You are creating and storing the password with:
$salted_hash = hash('sha256', $password.$site_salt.$p_salt);
But when you recover the password from your table you are encrypting to compare the password that is already encripted.
When you compare the passwords use $p_salt.
Related
Code Here is encrypting password but How I decrypt it or Compare it to login in laravel
Code where used
getsql(md5($_POST['regpassword'] . SALT), "default"),
md5 is hashing and it's not reversible you can't decrypt it you can only hash the password using the same algorithm and salt then compare the results to make sure that it's the correct password
When you're validating the password, you can do:
$hashed = md5($_POST['password'] . SALT);
$sql = "SELECT * FROM users WHERE username = '{$_POST['username']}' AND password = '$hashed'";
I've simplified this to show the important part of how to check the password, in reality you should use a prepared statement to prevent SQL injection.
Another way is to fetch the hashed password from the database, then compare it with the hashed+salted password that was given:
$hashed = md5($_POST['password'] . SALT);
$sql = "SELECT password FROM users WHERE username = '{$_POST['username']}'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row && $hashed == $row['password']) {
// user is validated
}
If you fix your method of storing passwords to use a more reasonable method than a static SALT, this second method can easily be updated. Instead of $hashed == $row['password'] you would use password_verify($_POST['password'], $row['password']).
I want my login password to be secured. So I came up to use the PHP's crypt() function to hash the password before inserting it to database. But Im having trouble when comparing the user input password from the converted hash password. Here's my code:
<?php
$password = 'hello_password';
# A higher "cost" is more secure
$cost = 10;
# Create a random salt
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
# Blowfish algorithm.
$salt = sprintf("$2a$%02d$", $cost) . $salt;
$salted_password = $password . $salt; // apply salt to password
# hash the password
$hash_password = hash('sha256', $salted_password);
$userInput = 'hello_password'; // suppose this is the user input password
if (hash('sha256',$userInput) == $password) {
echo "Password Verified.";
}
else {
echo "Incorrect Password";
}
?>
But it always displays Incorrect Password although my password is correct. I don't want to use "hash_equals" function as it is not supported with my current PHP version. Can someone help me with this ? Thanks
You're comparing a hashed user input to the actual user password. So of course this is never going to work.
You're basically asking if hash == 'hello_password'. A hash will never match that, that is the whole point of a hash. You also aren't using the salt with the user input.
You hash the actual password with a salt which is fine:
$salted_password = $password . $salt; // apply salt to password
# hash the password
$hash_password = hash('sha256', $salted_password);
So you need to hash the user input with the salt, the same way:
$salted_input = $userInput . $salt; // apply salt to user input
# hash the input
$hash_input = hash('sha256', $salted_input);
Then you can compare $hash_input with $hash_password.
You also aren't using a salt properly. The salt is supposed to be used in the storage of the password to prevent rainbow table attacks. Randomly generating a salt to apply to both the input and the password at the time of comparison is pointless.
I have searched through Internet and found the function for hashing the password. But
i'm having trouble to deal with hashed password stored in the the database. the function i'm using generate the random password as it is concatenated with the random generated salt.
the problem comes when a user wants to change his password.
current_password = random hashed password( which must match the one stored in db).
if(current_password == $db_password){
enter new password
}
the above condition wont be true since the password is always random.
my function
function cryptPass($input,$rounds = 9) {
$salt = "";
$saltChars = array_merge(range('A','Z'),range('a','z'),range(0,9));
for($i = 0;$i < 22; $i++){
$salt .= $saltChars[array_rand($saltChars)];
}
return crypt($input,sprintf('$2y$%02d$', $rounds).$salt);
}
$pass = "password";
$hashedPass = cryptPass($pass);
echo $hashedPass;
i have 3 column in my user table (id, username, password).
can any one tell me how to properly use this function,
or is there a best way to do this?
You want to store the $salt generated in the database along with the hashed password. Then when you come to check the password you will be able to get the salt from the database and use it in the hashing process again.
So your database table with have an extra column in it called "salt"
(id, username, password, salt)
You need to do the same steps, as you would for the login. Check if the entered old password matches the password-hash in the database, then create a hash from the entered new password and store it.
PHP already has a function password_hash() to create a hash, and a function password_verify() to check whether the entered password matches the stored password-hash.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
So your code would look something like this:
if (password_verify(current_password, $db_password))
{
enter new password
}
I'm trying to hash the password if you sign up on my website, but it doesn't work.
This is my code to hash the password upon signing up:
$escapedName = mysql_real_escape_string($_POST['user']);
$escapedPW = mysql_real_escape_string($_POST['password']);
$salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
$hashedPW = hash('sha256', $escapedPW . $salt);
Then I just insert it in a database (the hashed password and the salt).
For example, when I hash Sas, with the following salt:
abac7ad23185ad19967f0d13e962197962782f0b7ec32d9889c27a93a9e800fa
This is the hashed password:
8ca5c5f31fafbf382533dbcbfc22b3635d776ec7770c7eac58d8ef9f1fa3613c
But when I try to hash the password on log in, with the exact same password and salt, this becomes the hashed pass:
6eb4b16444f18cee19db32bd29a39970e3019c5b1972a982ae4cb9a59642dffc
This is the code I use to login:
$escapedName = mysql_real_escape_string($_POST['user']);
$escapedPW = mysql_real_escape_string($_POST['password']);
$saltQuery = mysql_query("SELECT salt FROM members WHERE user='{$escapedName}'");
while($result = mysql_fetch_assoc($saltQuery)) {
$salt = $result['salt'];
}
$hashedPW = hash('sha256', $escapedPW . $salt);
$sql = mysql_query("SELECT * FROM members WHERE user='$escapedName' AND pass='$hashedPW'; ");
while ($res = mysql_fetch_assoc($query2)) {
$username = $res['user'];
$PW = $res['pass'];
}
I hope it's not too much code and I also hope you will understand my question.
Sorry I can't comment but something tells me that there is a length restriction on the salt column in your database.
Example: The salt field might only allow a 64 characters while the generated salt might be longer therefore when you save the salt it gets trimmed which ultimately changes the hashed password.
If that's the case, you might want to trim the salt before saving it.
I'd advise using PDO to make queries against your database.
Your inputs to the hash function must be different for some reason or other.
Add log output messages that print your inputs before you hash for both use cases (create user and login). Also be sure to put quotes around the inputs in your logging to show whitespace issues.
Compare the raw inputs as well as the output of the hash function in both cases, and there will be a difference somewhere. If there is no difference, and the output of the hash is the same, then there is a problem in your query that is looking up the user in the login case.
Whatever you're doing, it's insecure if you WANT the hashes to be the same! See http://php.net/crypt for proper password hashing.
All you need:
function check_password($password) {
...//get db password to compare
if (crypt($post_password, $db_results[0]['password']) == $db_results[0]['password']) {
return true;
} else { return false; }
}
Hey guy's i'm trying to make a login system which uses MD5 encryption for the password. I have the encrypting to work and all it's just for some reason when i enter the password "palmer" into the login page and click the login button i made it send me to a page where it tells me encrypted password and using "palmer" as the password it outputs this "Duncan Logged in using password 4844fd4088ef5278ad18f892808ebda8 - palmer". THe password in the database when encrypted is "4669a6b46c8d891b373cfcd664dff6". Why are the two passwords different? I am using the same Salt(the salt is "a123b123".
Below is my code which encrypts password on register:
$password = $_POST['password'];
$md5pass = md5($salt.md5($password));
Below is my login code.
<?php
session_start();
include('config/config.php');
$email = $_POST['email'];
$password = $_POST['password'];
$pass2 = md5($salt.md5($password));
$check = mysql_query("SELECT `email`,`password` FROM user WHERE (`email`='$email' AND `password`='$pass2')") or die(mysql_error());
$count = mysql_num_rows($check);
//if($count == 1) {
$_SESSION['user'] = strtoupper($user);
//header('Location: /panel/index.php');
echo("Duncan Logged in using password $pass2 - $pass");
//} else {
//$_SESSION['errormsg'] = "<div id='error'><strong>Error:</strong> Invalid Username or Password!</div>";
//header('Location: index.php');
//}
?>
you have to store your salt – and please, use a random salt, this way two users with the same password will get a different digest! – somewhere for later use:
$salt = sha1(getRandomSalt());
$digest = sha1($password.$salt).'$'.$salt; // use sha1 instead of md5
later you can check the provided password with the same salt:
list($stored_pw, $stored_salt) = explode('$', $stored_digest);
if($stored_pw == sha1($user_provided_pw.$stored_salt)) {
echo 'user provided correct password';
}
You should really use bcrypt for this. There is more on bcrypt on previous Stack Overflow post How do you use bcrypt for hashing passwords in PHP?
bcrypt is considered the most secure way to implement password hashing with salt because it is slow - much slower than an MD5.
Just a little comment to knittl's solution from above:
You need to replace the line
if($stored_pw = sha1($user_provided_pw.$stored_salt)) {
by
if($stored_pw == sha1($user_provided_pw.$stored_salt)) {
to get it working.
(I tried to add it to knittl's post, but it says edits need to be at least 6 characters long)