Since this question is rather popular, I thought it useful to give it an update.
Let me emphasise the correct answer as given by AviD to
If you need fast, secure encrypted cookies in PHP, check out how Halite implements them. Halite relies on the libsodium PECL extension to provide secure cryptography.
store('index', $any_value);
$some_value = $cookie->fetch('other_index');
If you cannot install PECL extensions, ask your sysadmin or hosting provider to do it for you. If they refuse, you still have options.
The other answers instruct you to encrypt your data with openssl or mcrypt, but they're missing a crucial step. If you want to safely encrypt data in PHP, you must authenticate your messages.
Using the OpenSSL extension, the process you would need to follow looks like this:
(Before you even think about encryption) Generate a 128-bit, 192-bit, or 256-bit random string. This will be your master key.
Do not use a human-readable password. If you, for some reason, must use a human-readable password, ask Cryptography SE for guidance.
If you need special attention, my employer offers technology consulting services, including development of cryptography features.
random_bytes(openssl_cipher_iv_length('aes-256-cbc'))
$eKey
)$aKey
)openssl_encrypt()
with your IV and an appropriate modate (e.g. aes-256-ctr
) using your encryption key ($eKey
) from step 2.hash_hmac('sha256', $iv.$ciphertext, $aKey)
. It's very important to authenticate after encryption, and to encapsulate the IV/nonce as well.bin2hex()
or base64_encode()
. (Warning: This approach might leak cache-timing information.)$eKey
.If you want to see how this all looks together, see this answer which has sample code.
If this sounds like too much work, use defuse/php-encryption or zend-crypt and call it a day.
However, we have a requirement to implement a 'remeber me' feature. The accepted way to go about this is by setting a cookie. If the client presents this cookie, he or she is allowed access the system with (almost) equal rights as if he/she presented the valid username password combination.
Encryption is actually not the correct tool for this job. You want to follow this process for secure remember me cookies in PHP:
selector
which will be used for database lookups. (The purpose of a random selector instead of just a sequential ID is to not leak how many active users are on your website. If you're comfortable leaking this information, feel free to just use a sequential ID.)validator
which will be used to authenticate the user automatically.validator
(a simple SHA-256 hash will suffice).selector
and the hash of the validator
in a database table reserved for automatic logins.selector
and validator
in a cookie on the client.selector
and validator
.selector
.validator
.This is the strategy that Gatekeeper adopted for long-term user authentication and it is the most secure strategy proposed to date for satisfying this requirement.