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.

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

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来