Reputation: 984
I'm using this php script to store usernames and password to my MYSQL database:
$nombre = $_POST['username'];
$password = $_POST['password'];
$stringpass = md5( $password . 'AAA');
$size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
$salt = mcrypt_create_iv($size, MCRYPT_RAND );
mysqli->query("INSERT INTO users(username,salt,password) VALUES ('$nombre','$salt',SHA2(CONCAT('$salt','$stringpass'), 512))"))
The record is correctly created in MYSQL. However, when I try to login, this script does not recognize my password:
$nombre = $_POST['username'];
$password = $_POST['password'];
$stringpass = md5( $password . 'AAA');
$resultado = $mysqli->query("select * from users where username='$nombre' and password = SHA2(CONCAT(salt,'$stringpass'), 512)")
This returns no results for me. Any ideas on what can be missing? Perhaps is the reference to the salt field, but not sure how to do this.
Just let me clear out that this code isn't for any production environment. It's for a school project and only for demostration purposes on designing a simple user authentication script. This said, I would really like to know what can be wrong in this code, or what specific configuration do I need to check in my PHP/MySQL environment.
Upvotes: 0
Views: 1891
Reputation: 24071
The generated salt is a binary string, so you cannot just insert it to an SQL statement, you would have to use prepared statements or escaping.
Regardless of this problem, this is not a safe way to store passwords. The SHA-* algorithm is not appropriate to hash passwords, instead one should use a slow algorithm with a cost factor (BCrypt, PBKDF2).
PHP now offers a much easier way to generate safe password hashes with its password_hash() function (a compatibility pack for earlier versions is available too). The salt becomes part of the hash-value, so there is no need to store it separately in the database.
// 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);
Upvotes: 0
Reputation: 12213
I'm not sure what the exact problem is, but this may help.
Php provides a much simpler alternative that automatically generates salt and hash - the password_hash()
function. You just do password_hash($password, PASSWORD_BCRYPT);
, and it will generate a salt, hash the password with it, and append the salt to the front of the hash.
Here's the documentation page.
http://php.net/manual/en/function.password-hash.php
Upvotes: 4