I have a php(symphony) web application and an android application which access to the same database.The password field in the table is encrypted with symphony with Bcrypt and its value started with $2y$13,I used this code php to encrypt my password entered by the android application:
if(isset($_POST['password'])){
$password = $_POST['password'];
$pas_hash= password_hash("$password", PASSWORD_BCRYPT);
$sql = 'SELECT * FROM tbl_auth WHERE password = :pas_hash';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':pas_hash', $pas_hash, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount())
{
$result="true";
}
elseif(!$stmt->rowCount())
{
$result="false";
}
// send result back to android
echo $result;
}
The problem is that the value of pas_hash started with $2y$10 and when I used password_verify(), this function returns true result.
I didn't what's the problem because the final $result sent to my android application was false.
Thanks.
Okay, so if($stmt->rowCount()) is checking if the amount of rows is null or not, but it is not null, it is 0 because your result returned 0 rows.
Change your statement to if ($stmt->rowCount() > 0) and that should fix it.
Personally the way you are verifying your user(?) is a bit odd, it would be better to search the person's username, get their password from the database and use password_verify on the password you got from the user and the password you got from the database. This may not suit your functionality but it might aswell so take inspiration from the code below if you wish.
Example:
if(isset($_POST['username'])){
$username = $_POST['username'] // Or however you get the username.
$password = $_POST['password'];
$sql = 'SELECT * FROM tbl_auth WHERE username = :username';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(password_verify($password, $result['password'])
{
$result="true";
}
else
{
$result="false";
}
// send result back to android
echo $result;
}
Related
I'm trying to create a "registration" form using php and mysql. The registration form asks for username and password. If any field is empty, it will let the user know which one. If the username is in use, it will also let the user know.
I know the connection to the database is ok, because I created a user that was I manually added into the database.
The strange thing is that my code is working in Cloud9. But, it wont work on a VM instance installed on google cloud.
In cloud9, it adds the user into the DB. In the google instance, it wont.
Can anyone check this and tell me what I;m doing wrong?
Thanks.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$display = $_POST['display'];
$dbh = new PDO("mysql:host=localhost;dbname=mydb","root",NULL);
$stmt = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if($stmt->rowCount() == 0 and $username != null and $password != null){
$insert = $dbh->prepare("INSERT INTO users(username,password) VALUES(:username, :password)");
$insert->bindParam(':username', $username);
$insert->bindParam(':password', $password);
$insert->execute();
echo ("The user ".$username. " has been created.");
Try this, before all u need to check
if username and password is not empty because if username is empty i
cant make query valid to select username
check if username is in use
if username not in use, insert data into database
script
<?php
// error_reporting on
error_reporting(1);
ini_set('error_reporting', E_ALL);
$username = $_POST['username'];
$password = $_POST['password'];
// i commented $display variable because i don't see that u using it anywhere
//$display = $_POST['display'];
// database connection
$dbh = new PDO("mysql:host=localhost;dbname=mydb","root","");
// query
$stmt = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
// check if username and password is not empty
if ($username != '' && $password != '')
{
// check if username is in use
if($stmt->rowCount() > 1)
{
echo "Username in use, please choose another one.";
}
else
{
$insert = $dbh->prepare("INSERT INTO users(username,password) VALUES(:username, :password)");
$insert->bindParam(':username', $username);
$insert->bindParam(':password', $password);
$insert->execute();
// if last inserted id is true
if ($dbh->lastInsertId())
{
echo "The user ".$username. " has been created.";
}
else
{
echo "User not registered, please try again.";
}
}
}
else
{
echo "Please enter username and password.";
}
?>
I know this question is asked so many times and there are many tutorials about this thematic but I can't explain what I'm doing wrong. Could you pls tell me what is wrong in my code? The database connection works as it should, but I don't know where the problem is or if I understood something wrong, when I don't hash the password and entry it directly there is no problem. No matter what I entry my login will not work and always returns "false".Here is my code (note, I have a custom DBConnector class that handles variable types)
public function insertUser(){
if (isset($_POST['name']) && isset($_POST['password'])){
try
{
$name = $_POST['name'];
$password = $_POST['password'];
$db = CDatabase::getInstance();
//check if username is already in use
$db->prepare("SELECT * FROM user where LOWER(name) = LOWER(?)");
$db->bindParams(array($name));
$db->execute();
$result = $db->fetch();
//if no user with the same name was found
if ($result->num_rows == 0){
//insert user without password
$db->prepare("INSERT INTO user (name) VALUES(?)");
$db->bindParams(array($name));
$db->execute();
//get user_id of last inserted user because I use user_id as salt
//pls feel free to correct me if this is stupid
$user_id = $db->getLastInsertedId();
$salt = $user_id;
//hash password with user_id
$saltedHash = hash('sha256', $password, $salt);
var_dump($saltedHash);
//update user with password
$db->prepare("UPDATE user set password = ? where user_id = ?");
$db->bindParams(array($saltedHash, $user_id));
$db->execute();
//since I call this function via ajax true -> user is inserted correct
echo "true";
}else{
echo "Error: name is already in use";
}
}
catch(Exception $e)
{
$this->m_renderer->loadTemplate('error.html');
$this->m_renderer->assign(array('errorcode' => 6000, 'errormessage' => $e->getMessage()));
$this->m_renderer->render();
}
}
}
And this is my login function
public function loginUser(){
if (isset($_POST['name']) && isset($_POST['password'])){
try
{
$name = $_POST["name"];
$password = $_POST['password'];
$db = CDatabase::getInstance();
$db->prepare("SELECT * FROM user where LOWER(name) = LOWER(?)");
$db->bindParams(array($name));
$db->execute();
$result = $db->fetch();
if ($result->num_rows > 0){
$row = $result->fetch_assoc();
$salt = $row["user_id"]; //use user_id as salt
$saltedHash = $row["password"];
var_dump($password);
var_dump(hash('sha256', $password, $salt));
var_dump($saltedHash);
if (hash('sha256', $password, $salt) == $saltedHash) {
echo "correct";
} else {
echo 'Error: password incorrect';
}
}else{
echo "Error: username does not exist";
}
}
catch(Exception $e)
{
$this->m_renderer->loadTemplate('error.html');
$this->m_renderer->assign(array('errorcode' => 6000, 'errormessage' => $e->getMessage()));
$this->m_renderer->render();
}
}
}
And this is the output from my console
string(32) "��Ё�L}e�/���Z���O+�,�]l�� //insertUser hash('sha256', $password, $salt);
"
true
string(4) "test"
string(32) "��Ё�L}e�/���Z���O+�,�]l�� //loginUser hash('sha256', $password, $salt)
"
string(31) "????L}e?/???Z???O+?,?]l?? //this value is in my database
"
Error: password incorrect
I'm using the latest version of XAMPP on my local machineThank you very much
The problem is that hash() returns binary data, which you're apparently not handling/storing as binary data in the database, which corrupts the hash.
The bigger problem is that you're using hash() in the first place. The even bigger problem is that you're using it incorrectly. See its signature:
string hash ( string $algo , string $data [, bool $raw_output = false ] )
Nowhere does it accept a salt. What you set as $salt is actually $raw_output, which is why you're getting binary data from it.
A single unsalted SHA-256 round is also nowhere close to being secure for password storage; your hashed passwords are prime for a rainbow table attack, which probably already exists somewhere.
Stop using hash, use password_hash and password_verify instead. See their examples for how to use them exactly.
I have a problem with PHP function password_verify. I've written simple PHP function that uses _GET, takes 3 parameters: $user_unique_id, old_password and new_password. It verifies if old password and the password stored in database are the same. I use hash from my database and compare it with old password using password_verify() fucntion but it returns false even whem I'm 100% sure the passwords are the same. Can somebodyb help me with this problem? I've checked MySQL queries and all works very well. I return updated_at time which later I encode to JSON.
This is my function in main script changeuserpassword.php I call from link:
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// JSON Response Array
$response = array();
// Receiving The Post Params
$old_password = $_GET['old_password'];
$new_password = $_GET['new_password'];
$user_unique_id = $_GET['user_unique_id'];
// Change User Password
$user = $db->changeUserPassword($user_unique_id, $old_password, $new_password);
if ($user != false) {
$response["error"] = false;
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
$response["error"] = true;
$response["error_msg"] = "Podano nieprawidłowe stare hasło";
echo json_encode($response);
}
?>
This is the function I use in changeuserpassword.php main script. It is called changeUserPassword:
/**
* Change User Account Password
*/
public function changeUserPassword($user_unique_id, $old_password, $new_password) {
$stmt = $this->conn->prepare("SELECT user.`encrypted_password`
FROM `user`
WHERE user.`unique_id` = ?"); // Preparing SELECT Query To The `user` Table
$stmt->bind_param("s", $user_unique_id); // Binding With Params
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc(); // Fetching Rows From Query
$stmt->close();
$password_hash = $user["encrypted_password"]; // Decrypting Hashed Password
// Checking Currrent Password Identity With Decrypted Password
if (password_verify($old_password, $password_hash)) { // Old Password And Current One Are The Same
$encrypted_password = password_hash($new_password, PASSWORD_DEFAULT); // Hashing New Password
$stmt = $this->conn->prepare("UPDATE user
SET user.`encrypted_password` = ?, user.`updated_at` = NOW()
WHERE user.`unique_id` = ?");
$stmt->bind_param("ss", $encrypted_password, $user_unique_id);
$result = $stmt->execute();
$stmt-close();
// Checking For Succesfull UPDATE
if ($result) {
$stmt = $this->conn->prepare("SELECT user.`updated_at`
FROM `user`
WHERE user.`unique_id` = ?");
$stmt->bind_param("s", $user_unique_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc(); // Fetching Rows From Query
$stmt->close();
return $user;
}
} else { // Old Password And Current One Are Different
return false;
}
}
}
Edit
Here is my database screenshot:
My script runs but it always return false which means password_verify() returns false.
Solved
The problem was $stmt->close() statement. I used them too often and thats why the script didn't work.
After debugging with #anton86993 in a chat, we found the bug to be the use of too many $sql->close() statements, when they weren't needed.
There is no reason to have that many close statements, as PHP automatically closes the connection to SQL when the script is done. A reason to have a close statement could be to release a connection to SQL, if you have a limited amount of connection at once or the obvious one to release resources.
Hello i have a script for login and i'm using SHA512 for encryping pass. The thing is my script somehow doesnt fetch info with database table and i dont know why. My script returns "error_msg". Here is my code
<?php
session_start();
include ('engine/core/dbconfig.php');
$password=$_POST['password'];
$username=$_POST['username'];
if ($password='' or $username='') {
echo 'mandatory';
} else {
$stmt = $dbh->prepare("SELECT * FROM Admin_Local where Username=:username and Password=:hashed");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':hashed', $hash);
$hash = hash('sha512', $password);
$stmt->execute();
if ($row = $stmt->fetch()) {
$_SESSION['admin_local']=$row['ID_Admin'];
echo''.$_SESSION['admin_local'].'';
} else {
echo 'error_msg';
}
}
The line below is always false and assigns an empty line to the username and password. Change this line:
if ($password='' or $username='')
to
if ($password=='' or $username=='')
Also, you should use something like password_hash for hashing your passwords.
I have a PHP page that registers and logs in users. When I enable sha1, the user gets created and the encrypted password is stored in the DB, but they cannot log in. When I comment out the line to encrypt in both the user creation section as well as the login section, everthing works. Here is my code to create the user:
function add_member($nick_name, $email_address, $password) {
global $db;
$password = sha1($password);
$query = "INSERT INTO members
(nick_name, email_address, password)
VALUES
('$nick_name', :email_address, :password)";
$statement = $db->prepare($query);
$statement->bindValue(':email_address', $email_address);
$statement->bindValue(':password', $password);
$statement->execute();
$statement->closeCursor();
}
Here is my code to validate the user:
function is_valid_member($email_address, $password) {
global $db;
$password = sha1($password);
$query = "SELECT member_ID
FROM members
WHERE email_address = :email_address AND password = :password";
$statement = $db->prepare($query);
$statement->bindValue(':email_address', $email_address);
$statement->bindValue(':password', $password);
$statement->execute();
$valid = ($statement->rowCount() == 1);
$statement->closeCursor();
return $valid;
}
Again, when I comment out the "$password = sha1($password);" in both sections, everything works but the password is clear text.
Thanks!
try to debug like this, echo your $password = sha1($password); and check your database entry, might be your datatype length truncated some text in stored password