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.
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染