1

I was just wondering is it redundant to encrypt and sign a cookie? Isn't encryption enough? Why or why not?

If it's not redundant, I'm wondering if I'm going about this in the right direction. For simplicity's sake, what I've done is this:

$data = 'some data';
$encrypted_data = mcrypt_encrypt($cipher, $key, $data, $mode, $iv);
$signature = hash_hmac($algorithm, $data, $key);
$package = $encrypted_data . '|' . $signature;
setcookie('somecookie', $package, time()+60*60*24);

From what I basically understand is, you're hmac hashing the data and with a delimiter you're appending it onto your encrypted data? Then later you do all your validation and so on when you're checking the cookie. Am I approaching this correctly? Also, should all the keys for encryption and signing be nonces (single time used key) or is it enough for each of them to be a single global key shared by all? I apologize that this is becoming a 3-parter question. Hope that no one minds. Thanks a lot.

user1307016
  • 383
  • 1
  • 8
  • 17

1 Answers1

2

I was just wondering is it redundant to encrypt and sign a cookie? Isn't encryption enough? Why or why not?

Unless you're using a newer AEAD interface, encryption doesn't protect against chosen-ciphertext attacks.

From what I basically understand is, you're hmac hashing the data and with a delimiter you're appending it onto your encrypted data? Then later you do all your validation and so on when you're checking the cookie. Am I approaching this correctly?

What you've written here is an Encrypt and MAC construction. You want Encrypt then MAC instead.

- $signature = hash_hmac($algorithm, $data, $key);
+ $signature = hash_hmac($algorithm, $encrypted_data, $key);

Even better, don't write it yourself if you don't have to. Feel free to use sodium_crypto_secretbox() and sodium_crypto_secretbox_open() instead. See the examples here.

Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206