title: PHP-MYSQL encryption that is safe
body: <p>I'm working on a messagging app, and I would like to encrypt the messages the safest way possible.</p>
  
  <p>Currently I'm doing the following:</p>
  
  <p><strong>chatMessages table</strong></p>
  
  <pre><code>userId   | message
  ---------|---------------------
  1        | ENCRYPTED%withChatMasterKey%
  2        | ENCRYPTED%withChatMasterKey%
  ...
  </code></pre>
  
  <p><strong>chatUsers table</strong></p>
  
  <pre><code>userId   | chatMasterKey (it is encrypted aswell with users ID's)
  ---------|---------------------
  1        | ENCRYPTED%withUserId(1)%
  2        | ENCRYPTED%withUserId(2)%
  ...
  </code></pre>
  
  <p>The messages are encrypted with a random masterKey that are stored in the chatUsers table where with another encryption the masterKey is encrypthed but now the key is the user's Id</p>
  
  <p><strong>So to decrypt the messages, you have to do this in php:</strong></p>
  
  <pre><code>$message = $messagesArray[0]["message"];
  $chatMasterKey = decrypt($chatUser[0]["chatMasterKey"], withKey: $userId);
  $messageDecoded = decrypt($message, withkey: $chatMasterKey);
  </code></pre>
  
  <hr>
  
  <p><em>Tthat works well, if somebody hacks the dataBase then he would not be able to read out the messages.</em></p>
  
  <p>But is this safe? If someone hacks the .PHP files aswell, then he will be able to figure out the method I'm using and could be able to decrypt the messages.</p>
  
  <p>Is there a better way to encrypt messages?</p>
  
  <p>/ for security reasons I changed some details in the post /</p>