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?
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):
Cookie
class . Halite is a usability wrapper for libsodium, a modern cryptography library that now ships with PHP 7.2.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.