I am developing login and registration function for an android app. I have checked many tutorial that set password as md5, but I want a more secure way. I use crypt()
instead of md5
.
Howerver, I only can register and cannot login into application. How do I fix this? I replace the line
$password = md5($pass)
with
$password = crypt($pass)
Below is the code i found in example:
class DbOperations{
private $con;
function __construct(){
require_once dirname(__FILE__).'/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
/*CRUD -> C -> CREATE */
public function createUser($username, $pass, $email){
if($this->isUserExist($username,$email)){
return 0;
}else{
$password = crypt($pass);
$stmt = $this->con->prepare("INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES (NULL, ?, ?, ?);");
$stmt->bind_param("sss",$username,$password,$email);
if($stmt->execute()){
return 1;
}else{
return 2;
}
}
}
public function userLogin($username, $pass){
$password = crypt($pass);
$stmt = $this->con->prepare("SELECT id FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
public function getUserByUsername($username){
$stmt = $this->con->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s",$username);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
private function isUserExist($username, $email){
$stmt = $this->con->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
$stmt->bind_param("ss", $username, $email);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
}
crypt()
will return a time-stamp hashed string when you are not giving salt.
You may add a salt and that will make hashed string become the same anytime.
$password = crypt($pass,"SALT_HERE");
However, I suggest you use password_hash()
rather than crypt()
if you are using PHP 5 >= 5.5.0, PHP 7.
It is more security than using md5()
or crypt()
.
Example:
$input = 'apple';
$hashed = password_hash($input,PASSWORD_DEFAULT);
//return $2y$10$1y2ie2MTlKa44vGqHIT8QeOHRR.BdtVbBj7B9He.4zQpL93cgi4Jm
//that you need to store in somewhere
//Verify the password
if(password_verify($input,$hashed)){
//Password correct
}else{
//Password incorrect
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.