David 天宇 Wong
David 天宇 Wong

Reputation: 4197

User decryption/encryption in PHP | storing key in session

so I have this website that allows users to write every day. It then get stocked in a database in plain text. It's not a blog so everything is private, and the biggest complain I regularly get is that "I" could still read what they wrote. It was still not "perfectly" private. Also I don't want to be the one who leaked thousand of private diaries.

So here is my train of thought on how to rend it private only to them.

Is that secure ? Also what is the best way to encrypt/decrypt UTF-8 ?

Also if someone changes its password it has to decrypt/re-crypt everything.

Upvotes: 3

Views: 3792

Answers (3)

DeepBlue
DeepBlue

Reputation: 694

Do not use password to encrypt the key, password should never be used anywhere in the logic, and should only be read on login as a hash not plain text. You can user other things like user email to generate a key.

Upvotes: 0

Stoic
Stoic

Reputation: 10754

You should instead store the hash of the password in the SESSION.
Never store plain passwords anywhere - anywhere!!

Also, consider reading this stackoverflow thread: Secure hash and salt for PHP passwords

To hash the password, you can use this approach:

  • Generate a salt for a particular user (a salt is a random string of characters), and store it somewhere, or generate a global salt (in your use case)
  • Use the following function to generate a hash for the password, and store that hash in the SESSION

function generate_hash($password) {
   $salt = "<some random string of characters>"; // do not change it later.
   return md5($salt . $password);
}

For the encryption, you can use the mCrypt library. A typical algorithm can be:

$key = 'password to (en/de)crypt';
$string = 'string to be encrypted';

$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

var_dump($encrypted);
var_dump($decrypted);

Upvotes: 3

James Binford
James Binford

Reputation: 2883

You should be using some form of encryption. PHP provides mCrypt for this purpose. Point by Point:

  1. Saving a password in the clear in a $_SESSION is inherently insecure. At the very least, hash it in both the session and the database. Then you can compare the hashes to one another. Sensitive data should never be stored in the clear anywhere.
  2. You can simplify this by using mCrypt. However, I think the focus here is incorrect. Rather than hashing all of this "diary" text, I think you should be more focused on abstracting the user information from the text itself.
  3. No need to use their password. Just use a common key and use mcrypt for this.

I hope this helps!

Upvotes: 1

Related Questions