简体   繁体   English

PHP Cookie防篡改

[英]php cookie tamper-proofing

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? 使用它来篡改我的cookie是否安全? I include the time in the hashing to expire the cookie. 我在散列中包括了使cookie过期的时间。 is this a secure way of doing it? 这是一种安全的方法吗?

It's generally a bad idea to roll your own crypto . 推出自己的加密货币通常是一个坏主意。

Is it safe to use this to tamper-proof my cookies? 使用它来篡改我的cookie是否安全? I include the time in the hashing to expire the cookie. 我在散列中包括了使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. 不,您使用的是SHA256哈希值,而不是HMAC-SHA256,哈希值在很大程度上可以由攻击者提供。 Without HMAC, SHA256 is vulnerable to length-extension attacks . 没有HMAC,SHA256容易受到长度扩展攻击

Instead, consider (in order of preference): 相反,请考虑(按优先顺序):

  1. PASETO , which provides tamper-resistant tokens with a high security margin. PASETO ,它提供具有高安全裕度的防篡改令牌。 The only downside is that they're not immune to replay attacks. 唯一的缺点是他们不能不受重放攻击的影响。
  2. JWT , with HS256. JWT和HS256。 The linked library will allow you to securely only ever allow HS256, thereby side-stepping 99.9% of JWT security fails . 链接库将仅允许您安全地仅允许HS256,从而回避了99.9%的JWT安全性失败
  3. Halite's Cookie class . Halite的Cookie Halite is a usability wrapper for libsodium, a modern cryptography library that now ships with PHP 7.2. Halite是libsodium的可用性包装,libsodium是一个现代加密库,现已随PHP 7.2一起提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM