Encrypting cookies in PHP

后端 未结 5 2035
梦谈多话
梦谈多话 2021-01-11 15:48

How can i encrypt and later decrypt a value of a cookie in PHP (how secure will the encryption be )

相关标签:
5条回答
  • 2021-01-11 15:59

    There a variety of different ways to encrypt information in cookies and elsewhere. The strength of the encryption will vary by the method you choose to do the actual encryption. mycrypt is a good place to start. See this answer for an example of using mcrypt.

    I don't recommend putting anything sensitive in a cookie, even if it is going to be encrypted. Way too tempting for someone to crack. Try sticking to sessions if you can.

    0 讨论(0)
  • 2021-01-11 16:00

    If the cookie is encrypted securely (for example, with a server-stored secret that changes on a regular basis) I see no problem with storing useful data in the cookie. Why store it on the server? Make the client do some work for a change -- especially if it is preferences. Why should the server have to constantly store and retrieve data from a session file? What if you have hundreds of thousands of users pounding your site? Now you have to maintain hundreds of thousands of session files.

    0 讨论(0)
  • 2021-01-11 16:07

    I can think of a reasonable use for this. Suppose you have a large server farm, you're going to have a bottleneck at the database and/or memcached server for handling session requests.. "is this user logged in?"

    If you were to store the users session data as an encrypted value in the cookie, then you can prevent having to do quite a few read/writes and allow for an unlimited sized cookie store since there is 0 impact on your side other than being CPU bound for encryption/decryption of the cookie data.

    Ruby on Rails by default does this - although it only signs the data and does not encrypt it. There is an alternative implementation which encrypts the data with its own key and signature so you the user is not able to see what data you store in their session.

    0 讨论(0)
  • 2021-01-11 16:10

    I can not simply think of a situation where encrypting data in the cookie is useful. If you want to retain secret data about the user or his preferences, information, whatever, then store it on the server in files, in the session or in the database, but not in the client's computer.

    On the other hand, if you creating an authentication, then you should use sessions instead of creating secret encrypted cookie values. Sessions weren't implemented for nothing, they are the way to go.

    0 讨论(0)
  • 2021-01-11 16:16

    I am in full agreement with the other answers: If the data is truly sensitive it should be stored server side in a session, not in a cookie.

    As far as ways to encrypt cookie contents, the Suhosin PHP extension provides the ability to transparently encrypt all cookies. If you have the ability to install PHp extensions this may or may not be easier for you than writing your own encryption scheme.

    0 讨论(0)
提交回复
热议问题