Search code examples
phpsecurityencryptioncryptographysession-cookies

Is openssl_encrypt secure enough to create a session token?


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?


Solution

  • 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:

    • rc2-40-cbc is very, very weak
    • it is not an authenticated encryption
    • the IV is not for fun, you can't just put in zeroes because that worked
    • the result will not fit in a cookie if there is enough session data
    • the same session data would be encrypted to the same ciphertext
    • ...

    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.