php - 盐 : Hashed or plain text?

标签 php database hash

我想在数据库中的密码旁边存储一个(随机)盐。现在,问题是:

我应该将其存储为哈希值还是纯文本?有什么区别吗(更安全,更快?)?我应该付出多少努力来创建随机字符串?

示例代码:

    //Creating random salt
    $saltchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&()*+,-./:;<=>?@[]^_`{|}~";

    $salt = uniqid(rand(), true).str_shuffle($saltchars);
    // Or should the salt be hashed (md5 or sha512 for more security)
    // $salt = hash('sha512', uniqid(rand(), true).$staticsalt.str_shuffle($saltchars));
    //Create user (with salt & pepper)
$sqlquery = "INSERT INTO users (user, password, salt) VALUES('$id','".hash('sha512', $staticsalt.$accesskey.$salt)."','".$salt."');"; 
    $sqlresult = mysql_query($sqlquery); 

备案:登录脚本

    $sqlquery = "SELECT salt FROM users WHERE user='$id';"; 
    $sqlresult = mysql_query($sqlquery); 

    if (mysql_num_rows($sqlresult) == 1) { 

    $salt = (mysql_fetch_array($sqlresult));

//Check if the password is correct
    $sqlquery = "SELECT * FROM users WHERE user='$id' AND password='".hash('sha512', $staticsalt.$accesskey.$salt[0])."'";
    $sqlresult = mysql_query($sqlquery);
    unset($accesskey, $salt);

    //Check whether the query was successful or not
    if($sqlresult) {
    if(mysql_num_rows($sqlresult) == 1) 
        {echo 'Login successfull';}
        else {die('Error: wrong user ID/password');}
    }
   }

我知道有很多网站都在讨论盐的利弊。但是没有人回答盐是否应该加密——也没有人展示如何使用随机(!)盐(像我一样保存在数据库中)编写登录脚本。

所以作为一个 php 初学者我不知道这段代码是否安全?或者是否有任何技巧可以使其更快或更精简...谢谢!

最佳答案

没关系。您可以假设盐是公共(public)信息,因为如果攻击者知道盐,盐有助于防止攻击——彩虹表辅助字典攻击——不会变得更容易。您应该问问自己,为什么您认为首先加密盐是个好主意。

此外,您应该阅读以下内容:

关于php - 盐 : Hashed or plain text?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6559068/

相关文章:

git - git 标签对象的格式是什么以及如何计算它的 SHA?

c++ hash 在具有相同输入的 VS 2010 和 VS 2013 上返回不同的结果

security - 散列和加盐的密码是否可以防止字典攻击?

php - 维护数据库连接或在需要时连接?

java - 错误: method cleanCart in class Database cannot be applied to given types

database - db2数据库创建

javascript - 从 $.post() 函数中获取 2 个变量

php - PDO、$_GET 和从 MySQL 数据库中进行选择

php - imagecreatefromstring() [function.imagecreatefromstring] 此 PHP 版本中不支持 JPEG

php - 在每个 wordpress 帖子上设置 Rel ="Canonical"