douxie1692 2014-01-17 01:57
浏览 262
已采纳

Cookie加密/解密

I have a website where the user can choose for the website to "remember me" (AKA set a cookie) and per advice on this website, I switched my password encryption in the database to php's password_hash() function. Now, I can't just compare any old hash to one another so I use php's password_verify(). Password verify requires plaintext and a password hash.

How can I store the user's password in a browser cookie without it being plaintext?

  • 写回答

1条回答 默认 最新

  • dongwen7423 2014-01-17 02:09
    关注

    Storing the password in the cookie itself is a really bad idea, don't do that.

    At a very high level, I would:

    1. Generate a token (with something like md5) that consists of a couple unique (yet consistent) attributes for this user
    2. Store both the user ID and this token in the cookie (separated by some known delimiter)
    3. When the user visits your site, you can split out the ID and the token
    4. Use the ID to fetch the user record from the database, create a new token from the DB record, and compare with the cookie token

    So let's walk through this briefly. Say $hash is the password hash stored in the database, and you also have a $userId and $username variables for this user.

    I would generate a cookie that looks something like this:

    $token = md5($userId . $username . $hash);
    $cookie = $userID . "|" . $token; // 1|XXXXXXXX
    

    Now when a user visits your site and you retrieve this cookie:

    $parts = explode("|",$cookie);
    $userId = $parts[0];
    $token = $parts[1];
    

    Now you know who the user is claiming to be, but you need to verify.

    Fetch the user record from the database, and then regenerate the token and compare.

    // Assuming you just ran a SELECT query, and fetched the result into `$row`
    $dbToken = md5($row['userId'] . $row['username'] . $row['hash']);
    if($token == $dbToken) {
        // The user is who he claims to be! Log them in
    } else {
        // The cookie token didn't match our re-generated token, don't trust this cookie
    }
    

    Make sense? You will likely need to modify this a bit for your situation. Hopefully this helps get you going in a good direction at least.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看