doureng5668 2014-11-30 15:59
浏览 218

php cookie防篡改

I use this code on my website:

<?php
$pass = "61e7680d2ac47e5b9e3c82118fae6e3cfcddff285ac75bb82872bb01f24ac657";
function valCookie(){
    if (isset($_COOKIE['session'])){
        $cookie = json_decode(hex2bin($_COOKIE['session']), true);
        global $pass;
        $hash = hash('sha256', $_SERVER['REMOTE_ADDR'] . $cookie['uid'] . 
        $cookie['expiry'] . $pass);
        $uid = $cookie['uid'];
        if ((hash_unique($hash, $cookie['hash'])) && ($cookie['expiry'] > time())){
            return $uid; //return user id.
            }
        }
    }
function hashCookie($uid, $expiry){
    global $pass;
    $cookie['uid'] = $uid;
    $cookie['expiry'] = $expiry;
    $cookie['hash'] = hash('sha256', $_SERVER['REMOTE_ADDR'] . $cookie['uid'] . 
    $cookie['expiry'] . $pass);
    $hexCookie = bin2hex(json_encode($cookie));
    setcookie("session", $hexCookie, $expiry);
    if(strlen($uid)){
        return true;
        }
    }
?>

Is it safe to use this to tamper-proof my cookies? I include the time in the hashing to expire the cookie. is this a secure way of doing it?

  • 写回答

1条回答 默认 最新

  • douyue8364 2018-10-04 05:43
    关注

    It's generally a bad idea to roll your own crypto.

    Is it safe to use this to tamper-proof my cookies? I include the time in the hashing to expire the cookie. is this a secure way of doing it?

    No, you're using a SHA256 hash of values that can largely be provided by attackers instead of HMAC-SHA256. Without HMAC, SHA256 is vulnerable to length-extension attacks.

    Instead, consider (in order of preference):

    1. PASETO, which provides tamper-resistant tokens with a high security margin. The only downside is that they're not immune to replay attacks.
    2. JWT, with HS256. The linked library will allow you to securely only ever allow HS256, thereby side-stepping 99.9% of JWT security fails.
    3. Halite's Cookie class. Halite is a usability wrapper for libsodium, a modern cryptography library that now ships with PHP 7.2.
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料