The idea is to encrypt a string containing session data (username and token expiry) and store it in a cookie. Whenever an HTTP request comes from the client, the backend checks if it can decrypt the token in the cookie and then queries the DB to check if the username exists and is allowed to access the target resource:
// create token
$token = openssl_encrypt($username . "::" . $expiry, "rc2-40-cbc", $key, 0, "00000000");
// then store in cookie
'::' is just a delimiter.
// on http request, verify token
$decryptedToken = openssl_decrypt($token, "rc2-40-cbc", $key, 0, "00000000");
if($decryptedToken != false) // token is valid
// extract data
$tokenValues = explode("::", $token);
$username = $tokenValues[0];
$tokenExpiry = $tokenValues[1];
// then validate username and expiry
Is this safe?
Your code is absolutely insecure for multiple reasons. Please do not implement crypto without a basic understanding of what you are doing.
Using your method, the session data in the db would be cracked in less than a day with hardware that you have at home.
A few problems:
Please note that the solution is not changing the cipher and adding an IV. The solution is to use a well-known and tested library that does this for you.
The concept btw could work, but it has to be correctly implemented.