Search code examples
javaencryptionaeshmacdata-integrity

HMAC after encryption solution in Java


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!


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.