dqrnsg6439 2012-04-27 07:22 采纳率: 100%
浏览 29
已采纳

too long

So I'm in the process of learning PHP and am working on a login page. I already figured out how to register a new user using a SHA256 to hash $salt+$password. I know there are slower encryption methods like bcrypt but for learning purposes I'm just using SHA256. My question is, after using this to encrypt:

function HashPassword($password) {
  $salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)); 
  $hash = hash("sha256", $salt . $password); column
  $final = $salt . $hash;
  return $final;
}

using prepared statements, what is the best way to retrieve the hash password from the database so I can validate it using a function like this?

function ValidatePassword($password, $hash_pass) {

  $salt = substr($hash_pass, 0, 64); 
  $trueHash = substr($hash_pass, 64, 64); 
  $reHash = hash("sha256" , $salt . $password); 

  return $reHash == $trueHash;
}
  • 写回答

2条回答 默认 最新

  • drny60365 2012-04-27 07:34
    关注

    You basically save the password hashed with a salt to make it not recognizable.

    In case your database gets hacked at some point, the hacker can't read the password directly. Instead he will have to recreate the hashed value.

    If you don't use a different (random) salt for each user, the hacker will only have to create one table with all possible hash values and compare that to your saved hashed passwords.

    If each password, however, has a different salt added to the password, before hashing, the hacker has to create a new table for each single password, thus increasing the effort needed to get the real passwords a lot. One hopes that this will make in inefficient or too costly for the hacker.

    For you as a coder that wants to validate login credentials you have to follow the following pattern:

    1. Get the salt saved in the database.
    2. Compute the has value of the concatenated hash = salt + password
    3. Compare the computed has with the saved one hash === savedHash
    4. If they are the same, it was the valid password. If not, it was a wrong password.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图