Should I add a hash to the encrypted cookie to additionally verify the integrity of the data

60 Views Asked by At

I'm currently working on implementing cookie-based session management in my web application. Up until now, I've set up two methods to encrypt/decrypt the cookie while storing the initialization vector in the cookie itself. cookieEncryptionKey returns 32-byte long hash of a key stored externally in a config file.

class Auth 
{

    const COOKIE_TTL = 3600;
    const COOKIE_CIPHER = 'aes-256-cbc';

    private function encryptCookie(string $value)
    {
        $iv_length = openssl_cipher_iv_length(self::COOKIE_CIPHER);
        $iv = openssl_random_pseudo_bytes($iv_length);
        $encrypted = openssl_encrypt($value, self::COOKIE_CIPHER, $this->cookieEncryptionKey(), 0, $iv);

        return base64_encode($encrypted . '::' . $iv);
    }

    
    private function decryptCookie(string $value)
    {
        list($encrypted_data, $iv) = explode('::', base64_decode($value), 2);

        return openssl_decrypt($encrypted_data, self::COOKIE_CIPHER, $this->cookieEncryptionKey(), 0, $iv);
    }

}

Are there any major security flaws in such implementation? And should I add extra data integrity checks by including e.g. a hash_hmac signature in the cookie?

My understanding is that it is not necessary because an encrypted message cannot be tampered without knowing the original encryption key.

0

There are 0 best solutions below