I need to do some encryptions in the private zone of my website and I want to bcrypt the user's password.

Is it safe to store the password in the session when user does the login, so that I can use it later?

  • 3
    Possible duplicate of Do you need to encrypt session data?. Also, why not just use a surrogate key and store that instead of the user's password?
    – Polynomial
    Commented Aug 21, 2012 at 14:33
  • @Polynomial maybe OP uses password for file encryption Commented Aug 21, 2012 at 15:04

2 Answers 2


Don't store the password in the session variables. Instead, use a surrogate key.

For example:

  1. Generate a random key. This is your surrogate key.
  2. Use that key to encrypt whatever data you need.
  3. Generate a storage key from your password, using an appropriate key-derivation function (e.g. PBKDF2 or bcrypt).
  4. Encrypt the surrogate key with the storage key. If the two keys are of equal length, a bitwise xor of the two is an ideal form of encryption, since it's simple and cannot be broken without knowing one of the keys.
  5. Store the encrypted surrogate key.

When the user logs in, you do the following:

  1. Compute the storage key from the password.
  2. Use the storage key to decrypt the encrypted surrogate key.
  3. Store the decrypted surrogate key in your session variable.
  4. Use the surrogate key to decrypt the data as necessary.
  5. Destroy the decrypted surrogate key when the session ends.

If an attacker gets read access to session data stored in your /tmp directory, they might extract surrogate keys. However, they will not be able to get at the user's password. Whilst this doesn't protect the data you're encrypting on the server, it does prevent unauthorised access to the user's account, and stops the attacker from exploiting cases where the user has used the same password elsewhere.


If you want to use PHP securely, you should have the Suoshin Hardened PHP patch installed. (Any hosting company worth dealing with will already have it on their servers). This patch includes functionality that encrypts the session data automatically, which should be sufficient to protect you from certain kinds of attack.

But session hacks are just one item in a hackers' toolbox, and passwords are a primary target, so they should not be treated as something your program should hang on to (even in memory) for the any amount of time; a password should be hashed as soon as possible after input and the password string itself cleared immediately.

So my answer to your question would be no, you shouldn't be considering holding onto a password for re-use later.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .