PHP salt and hash SHA256 for login password

后端 未结 6 2298
南方客
南方客 2020-12-23 17:19

I\'ve made encrypting of the password in my register script and they are stored in the database, and I have to use them to login, so I would want to use the unencrypted ones

相关标签:
6条回答
  • 2020-12-23 17:57

    According to php.net the Salt option has been deprecated as of PHP 7.0.0, so you should use the salt that is generated by default and is far more simpler

    Example for store the password:

    $hashPassword = password_hash("password", PASSWORD_BCRYPT);

    Example to verify the password:

    $passwordCorrect = password_verify("password", $hashPassword);

    0 讨论(0)
  • 2020-12-23 18:03
    array hash_algos(void)
    
    echo hash('sha384', 'Message to be hashed'.'salt');
    

    Here is a link to reference http://php.net/manual/en/function.hash.php

    0 讨论(0)
  • 2020-12-23 18:06

    You can't do that because you can not know the salt at a precise time. Below, a code who works in theory (not tested for the syntaxe)

    <?php
    $password1 = $_POST['password'];
    $salt      = 'hello_1m_@_SaLT';
    $hashed    = hash('sha256', $password1 . $salt);
    ?>
    

    When you insert :

    $qry="INSERT INTO member VALUES('$username', '$hashed')";
    

    And for retrieving user :

    $qry="SELECT * FROM member WHERE username='$username' AND password='$hashed'";
    
    0 讨论(0)
  • 2020-12-23 18:08

    These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

    Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

    Save a password hash:

    $options = [
        'cost' => 11,
    ];
    // Get the password from post
    $passwordFromPost = $_POST['password'];
    
    $hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);
    
    // Now insert it (with login or whatever) into your database, use mysqli or pdo!
    

    Get the password hash:

    // Get the password from the database and compare it to a variable (for example post)
    $passwordFromPost = $_POST['password'];
    $hashedPasswordFromDB = ...;
    
    if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
        echo 'Password is valid!';
    } else {
        echo 'Invalid password.';
    }
    
    0 讨论(0)
  • 2020-12-23 18:16

    I think @Flo254 chained $salt to $password1and stored them to $hashed variable. $hashed variable goes inside INSERT query with $salt.

    0 讨论(0)
  • 2020-12-23 18:19

    You couldn't login because you did't get proper solt text at login time. There are two options, first is define static salt, second is if you want create dynamic salt than you have to store the salt somewhere (means in database) with associate with user. Than you concatenate user solt+password_hash string now with this you fire query with username in your database table.

    0 讨论(0)
提交回复
热议问题