Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • When they log in : key = sha1(salt + password) and store this key in a SESSION (how secure is that ?)

  • When they save their text : encrypt it with their $_SESSION['key'] before saving it to the database

  • When they read something they've saved, decrypt it with their $_SESSION['key'] before displaying it.

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.

like image 213
David 天宇 Wong Avatar asked Sep 11 '26 23:09

David 天宇 Wong


1 Answers

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);
like image 77
Stoic Avatar answered Sep 13 '26 13:09

Stoic