Does it use PDO and prepared instructions for logging in securely?

Once again, we're looking for some help with PHP security and the login system. I wonder if I did it right here. If I was not specific enough, please ask, any help is much appreciated. I am trying to create a secure login system, for training purposes only. here is the code:

require("constants.php");
$DBH = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

function createSalt() {
    $length = mt_rand(64, 128);
    $salt = '';
    for ($i = 0; $i < $length; $i++) {
        $salt .= chr(mt_rand(33, 255));
    }
    return $salt;
}
//Salt function created by ircmaxell

function registerNewUser() {
    //Check to see if     Username Is In Use//
    $q = $DBH->prepare("SELECT id FROM users WHERE username = ?"); 
    $username = filter_var($username, FILTER_SANITIZE_STRING);
    $data = array($username);
    $q->execute($data);
    $row = $q->fetch();

    if ($row === false) { 
        //If Username Is Not Already In Use Insert Data//
        $hash = hash('sha256', $pass);
        $salt = createSalt();
        $hash = hash('sha256', $salt . $hash . $pass);  //UPDATED
        $data = array($username, $hash, $salt);
        $qInsert = $DBH->prepare(
            "INSERT INTO users (username, password, salt) values (?, ?, ?)"
        );
        $qInsert->execute($data); //Inserts User Data Into Table//  
    }
}
+2
source share
2 answers

This is good so far. I have three suggestions:

  • Choose a longer salt
  • Do not store the salt and password collector separately
  • If your database connection does not match localhost, use a different database connector: PDO does not yet support SSL connections.

: , , " ". - , , .

EDIT # 2: : " ". - . - (64 ), [0-9a-f], ( ircmaxell ) . , (96 - 128 ) ():

$hash = hash('sha256', $pass);
$salt = substr(hash('sha256', mt_rand(0, 1337)), mt_rand(0, 31), 32);
$hash = $salt . hash('sha256', $salt . $hash . $pass);
+3

. -:

$hash = hash('sha256', $pass);
$salt = createSalt();
$hash = hash('sha256', $salt . $hash . $pass);

, ( SHA-256 ). , foo, bar sha256... $hash , , - :

$hash = hash('sha256', 'foo'); // "test" for example
$hash = hash('sha256', 'bar'); // "test" since it a collision

$newHash = hash('sha256', $salt . $hash); //The same for both foo and bar!

, , ...

: , (-):

function createSalt() {
    $length = mt_rand(64, 128);
    $salt = '';
    for ($i = 0; $i < $length; $i++) {
        $salt .= chr(mt_rand(33, 255));
    }
    return $salt;
}

( ), , ( ). , ISO-8859-1 (Latin-1). UTF-8. , 255 127 ( )...

+2

Source: https://habr.com/ru/post/1783224/


All Articles