-2

I want to improve my login system, by adding "Remember me" function. I actually made it, everything works fine, but now I want to upgrade it, by saving only md5 hashed values to cookies, so users can't edit them. But when I hash the string and store it to cookie and then hash it again, it doesn't return original string, but different hash. Is there any way I can achieve this? Code:

Setting cookie (this works fine):

$userCrypted = md5($_SESSION['username']);
if(!empty($remember)) {setcookie('remember', $userCrypted ,time()+60*60*24*365);}

Using cookie value to extract data from database (this doesn't work):

if(isset($_COOKIE['remember'])) {
        $user = $_COOKIE['remember'];
        $user = md5($user);
        $queryCookie  = "SELECT * FROM `users` WHERE `username` = '$user'";
        $resultCookie = mysqli_query($link, $queryCookie) or die(mysqli_error($link));
        while ($output = mysqli_fetch_object($resultCookie)) {
            //data  extraction

        }
user3560463
  • 147
  • 2
  • 10
  • Why would hashing a hash give you the original string? – Quentin May 10 '14 at 11:55
  • Is your username column on your database really holding a hashed value? – Mark Baker May 10 '14 at 11:56
  • 1
    It is trivial for a user to pick any username they like, md5 it, then store it in a cookie BTW. The security you get from this is close to nil. – Quentin May 10 '14 at 11:57
  • I don't have it hashed in database. But then, how can I prevent users from editing cookies, so they can't log in as other user? Should I save password to the cookie too? – user3560463 May 10 '14 at 11:59
  • 2
    You can't prevent users from editing cookies, and never store passwords in a cookie; but you can add a unique value in another cookie that validates against a rememberId column on the database along with the username and both must match to be valid – Mark Baker May 10 '14 at 12:01

1 Answers1

0

MD5 is not a reversible function. It's designed to be a one-way function; on other words, that it is computationally infeasible to obtain a preimage given a hash (ie, to find m given MD5(m)). If you want to prevent the user from modifying the cookie, append a MAC (eg, HMAC-SHA256) to the username and verify it before use.

As a cryptographic hash function, MD5 is considered broken because of flaws found in its collision and pre-image resistance, so it's recommended that MD5 not be used in new code. SHA-256 is currently the most common replacement.

user3553031
  • 5,615
  • 1
  • 18
  • 39