Question

I want to encrypt a cookie and make sure the cookie is not modified so I use HMAC for encrypted cookie.

There are a few ways to implement:

1. HMAC on encrypted cookie

String encryptedCookie = AES ( cookie )
String mac = HMAC ( encryptedCookie )

-- Persist cookie with value: encryptedCookie + ":" + mac

2. HMAC on encrypted cookie & HMAC's sercet key

String encryptedCookie = AES ( cookie )
String mac = HMAC ( encryptedCookie + ":" + Hmac's secretKey )

-- Persist cookie with value: encryptedCookie + ":" + mac

3. HMAC on encrypted cookie & some unguessable STATIC data

String encryptedCookie = AES ( cookie )
String mac = HMAC ( encryptedCookie + ":" + java.sql.ResultSet.class.getName() )

-- Persist cookie with value: encryptedCookie + ":" + mac

Anyone has any ideas? Which one is better? OR what is your solution? Thank you!

Was it helpful?

Solution

The HMAC function should already be keyed. So normally HMAC is shown as HMAC(K, M) where K is the key and M is the message. So candidate 2 does not make sense in that regard; it would mean that the key K is included 3 times in the calculation (as the key is used two times in HMAC itself).

Using a cookie with unguessable data does not make sense either, for the same reason. Part of the input of HMAC is the key K, which is already unguessable data. So you would not gain any security, and you would be complicating your protocol.

Now AES should be used in CBC or CTR mode. ECB mode of encryption is unsafe. So that means you require a random IV (CBC) or a unique IV (CTR). This IV should be part of the HMAC, otherwise it is still possible for an attacker to alter the plaintext you get after decryption.

OTHER TIPS

Options 2 and 3 are effectively the same assuming the static data is truly unguessable (and the same length etc). If you are seriously concerned about somebody modifying the cookie then option 2 is better as (assuming the secret key is not shared) it would allow you to detect if changes had been made to the cookie and would prevent somebody from changing the cookie and then rerunning the hash to spoof the mac. In practice, if the AES key is not accessible and the data in the cookie has some semantic meaning, you would likely be able to detect modifications to the encrypted cookie as it would decrypt to something meaningless. From a security perspective though, option 2 would provide the greatest assurances that the data hadn't been modified.

All of that said, I'm making a number of assumptions about your setup that may or may not be true.

Edit I evidently misunderstood the question with regards to the key data and did not clearly state enough of my assumptions. @owlstead's is a better answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top