login php hash and salt

Parth 8 years ago
<?php 

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "geosafe";

// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}


 function doLogin($u,$p,$con){
      
     $con; 
       //  $hosteo = new Host(1);
        //$this->set_conexion($hosteo->datos['localhost'],$hosteo->datos['root'],$hosteo->datos[''],$hosteo->datos['geosafe']);

         $consulta ='SELECT u.id as llave, u.name as nombre, u.hashedPassword as hashed,u.salt as salto,u.admin as estado FROM users u WHERE u.email="'.$u.'"';
        
       // $result = $this->sql_con->query($consulta);
        $result = mysqli_query($con, $consulta);
        $dato['estado'] = false;
        if($result === false) {
          
            trigger_error('Ha ocurrido un error');
        }
        
        else{
            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                echo  $row['hashed'].'<br>';
              $data = $p;
             //$key = sha1($p,TRUE);
              $key = hexToStr($row['salto']);

             $hashed = hash_pbkdf2('sha1',$data, $key,1000,24,true);    
             echo   strToHex($hashed);
              if (strToHex($hashed)==$row['hashed']){
                $dato['estado'] = true;
                session_start();
                $_SESSION['loginstate'] = 1;
                print_r($row);
              }
             
            }
        }
      // array_push($con,$dato);

    }
    
     function strToHex($string){
        $hex='';
        for ($i=0; $i < strlen($string); $i++){
            $hex .= dechex(ord($string[$i]));
        }
        return strtoupper($hex);
    }


     function hexToStr($hex){
        $string='';
        for ($i=0; $i < strlen($hex)-1; $i+=2){
            $string .= chr(hexdec($hex[$i].$hex[$i+1]));
        }
        return $string;
    }
    
    echo $data = doLogin('admin@demo.com', '123',$con);
    
    
?>

This is sample code witch i use and get output

  traccar database = 58F44CB8291BBDD6495BAF3587D2C6DF56C7A6A812529F0A
  OutPut          = 58F44CB8291BBDD6495BAF3587D2C6DF56C7A6A812529FA
paul84 8 years ago

Mihir, this is probably happening during your conversion.

Use the php function bin2hex() / hex2bin() to convert to and from HEX and a binary string.

Parth 8 years ago

Thank You so much . it's working perfectly .

adirahman 8 years ago

hello mihir can help login with php my code :

session_start();
error_reporting('E_ALL');
include 'lib/db.php';


if ($_SESSION){
	header('location:page.php');
}
if (isset($_POST['masuk'])){
   
    $email = $_POST['email'];
    $userpassword = $_POST['hashedpassword'];



	$sql = "select email,hashedpassword from users where email= '$email'  ";
	$result = mysqli_query($link,$sql);
	

	while($row = mysqli_fetch_array($result))
	{
		$data = $userpassword;
		$key = hex2bin($row['salt']);
		$hashed = hash_pbkdf2('sha1',$data, $key,1000,24,true);

		if (bin2hex($hashed)==$row['hashedpassword']){
                		//session_start();
                		//$_SESSION['email'] = $email;
            		$_SESSION['hashedpassword'] = $userpassword; 
            		header('location:page.php');
             		 }
	}




}

function strToHex($string){
        $hex='';
        for ($i=0; $i < strlen($string); $i++){
            $hex .= dechex(ord($string[$i]));
        }
        return strtoupper($hex);
    }

function hexToStr($hex){
        $string='';
        for ($i=0; $i < strlen($hex)-1; $i+=2){
            $string .= chr(hexdec($hex[$i].$hex[$i+1]));
        }
        return $string;
    }
Priyanka Mittal 7 years ago

Please help me ...
I want hash and salt for password using php in traccar for insert data in traccar user table.

Anton Tananaev 7 years ago

I would recommend you to use API because if you manually insert data into the database, it won't take effect until you restart Traccar service. Traccar has internal cache.

OurAppsWorld 9 months ago

Login Api

<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

require_once 'dbCon.php';

$input = json_decode(file_get_contents("php://input"), true);

if (empty($input['email']) || empty($input['password'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Email and password are required']);
    exit;
}

$email = trim($input['email']);
$password = $input['password'];

try {
    $stmt = $pdo->prepare("SELECT * FROM tc_users WHERE email = :email LIMIT 1");
    $stmt->execute(['email' => $email]);
    $user = $stmt->fetch();

    if (!$user) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Invalid credentials']);
        exit;
    }

    // ✅ Traccar v6.5 uses 1000 iterations, 24-byte salt + hash, hex encoded
    $expectedHash = strtolower($user['hashedpassword']);
    $saltHex = strtolower($user['salt']);
    $calculatedHash = bin2hex(hash_pbkdf2('sha1', $password, hex2bin($saltHex), 1000, 24, true));

    if ($calculatedHash !== $expectedHash) {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid credentials',
            'debug' => [
                'expected' => $expectedHash,
                'calculated' => $calculatedHash,
                'used_salt' => $saltHex,
                'input_password' => $password
            ]
        ]);
        exit;
    }

    // Remove sensitive info
    unset($user['hashedpassword'], $user['salt']);

    echo json_encode([
        'success' => true,
        'message' => 'Login successful',
        'user' => [
            'id' => (int) $user['id'],
            'name' => $user['name'],
            'email' => $user['email'],
            'readonly' => (bool) $user['readonly'],
            'administrator' => (bool) $user['administrator'],
            'phone' => $user['phone'],
            'map' => $user['map'],
            'latitude' => $user['latitude'],
            'longitude' => $user['longitude'],
            'zoom' => $user['zoom'],
            'coordinateformat' => $user['coordinateformat'],
            'disabled' => (bool) $user['disabled'],
            'expirationtime' => $user['expirationtime'],
            'devicelimit' => (int) $user['devicelimit'],
            'userlimit' => (int) $user['userlimit'],
            'devicereadonly' => (bool) $user['devicereadonly'],
            'limitcommands' => (bool) $user['limitcommands'],
            'login' => $user['login'],
            'poilayer' => $user['poilayer'],
            'disablereports' => (bool) $user['disablereports'],
            'fixedemail' => $user['fixedemail'],
            'totpkey' => $user['totpkey'],
            'temporary' => (bool) $user['temporary'],
            'attributes' => $user['attributes']
        ]
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()]);
    exit;
}
?>