Best cookies questions in July 2011

Checking if user has changed cookie value, manually

6 votes

I am busy with a login system for my project.

Just for an extra step to the security.. How can I check/detect if a user has manually changed a cookie value?

Is there some easy way of doing this? Or do I have to set an extra Session variable and match it up with that? With this being said, is a normal ASP.Net Session traceable by the browser? And viewable to the user?

Thanks.

You could append a digital signature to the cookie value and check the signature when you read it back. That way, if the cookie value is tampered with it will be very apparent.

private string sign(string hashStr, byte[] secret) 
{
    // Compute the signature hash
    HMACSHA1 mac = new HMACSHA1(secret);
    byte[] hashBytes = Encoding.UTF8.GetBytes(hashStr);
    mac.TransformFinalBlock(hashBytes, 0, hashBytes.Length);
    byte[] hashData = mac.Hash;

    // Encode the hash in Base64.
    string hashOut = Convert.ToBase64String(hashData);

    return hashOut;
}

Edit: Fixed the encoder so it's explicitly UTF-8.

As usual, you should also be sure to add some salt to your string before calling this, see: Secure hash and salt for PHP passwords