php – 使用sha1和salt存储密码

我有一个简单的注册脚本在PHP完成,我只是好奇,如果我这样做的方式足够安全,以存储用户密码.我正在生成一个32位随机盐并将其附加到sha1哈希密码.

//create new validator object
    $validator = new data_validation();
    //validate user input
    $firstName = $validator->validate_fname($firstName); //is the first name a string?
    $lastName = $validator->validate_lname($lastName); // is the last name a string?
    $username = $validator->validate_username($username); // is the username a string?
    $email = $validator->validate_email($email); //is the email in valid format?

    //make sure there isn't duplicate emails
    $valQuery = $link->query("SELECT email FROM users WHERE email = '" .$email. "'");

    if ($valQuery->num_rows == 1) {
        echo "An email is already registered with that address";
        return false;
    }

    // generate a random salt for converting passwords into sha1
    $salt = $link->real_escape_string(bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)));
    $saltedPW =  $password . $salt;
    $hashedPW = sha1($saltedPW);

    mysqli_connect($db_host, $db_user, $db_pass) OR DIE (mysqli_error());
    // select the db
    mysqli_select_db ($link, $db_name) OR DIE ("Unable to select db".mysqli_error($db_name));

     // our sql query
    $sql = "INSERT INTO users (first_name, last_name, username, email, password, salt) VALUES ('$firstName', '$lastName', '$username', '$email', '$hashedPW', '$salt');";

    //save the updated information to the database          
    $result = mysqli_query($link, $sql) or die("Error in Query: " . mysqli_error($link));

    if (!mysqli_error($link)) 
    {
        $row = mysqli_fetch_assoc($result);
        $_SESSION['user_id'] = $row['user_id'];
        $_SESSION['loggedin'] = TRUE;
        header("Location: ../home");
    }

此外,我正在使用程序和oop php的组合.其中大部分都是在过程中完成的,但是有一些oop类,比如你在上面的脚本中看到的验证类.这是否会导致使用这两种样式的性能问题?

解决方法:

不.停止你正在做的事情,阅读How to securely hash passwords,然后阅读Secure hash and salt for PHP passwords

最重要的是:

  • Use scrypt when you can; bcrypt if you cannot.
  • Use PBKDF2 if you cannot use either bcrypt or scrypt.

有关PBKDF2,bcrypt和scrypt的比较,请参阅this answer.

另请参阅经常链接的文章How To Safely Store A Password

[MD5, SHA1, SHA256, SHA512, SHA-3, etc] are all general purpose hash functions, designed to calculate a digest of huge amounts of data in as short a time as possible. This means that they are fantastic for ensuring the integrity of data and utterly rubbish for storing passwords.

PHPass可能是在PHP中进行bcrypt散列的最简单方法.如果你愿意,也可以使用crypt function和CRYPT_BLOWFISH进行do it the hard way,但要注意有很多方法可以解决它,并且界面相当神秘(就像你指定盐值一样).

上一篇:sqlserver中的MD5和sha1加密算法


下一篇:SHA1加密算法的java实现