处理联系表单的PHP脚本上的文件加密

Hey programmers of the world! I've created a simple HTML contact form (name,email,main message and a radio button), that the input is handled by a PHP script that it sends the strings to my mail server and then echo the input on a simple dat file that lies on my server. As you can imagine the data that is written to the dat file is in plain text. Now, I have two questions to make. What would be the best way to add some form of security on this system ? Would it be first passing the data to the file and then encrypting it or first encrypting the strings and then passing it to the file ?

Either way, what would be the best way to implement these security techniques ? If it is possible I could really help myslef if you posted an example code.

Thanks for all the answers!

Let's suppose that the server gets compromised and I do not want the content of the file be easily read.

That'd be quite a breach, and the only way to protect data on the server in this scenario is if the server itself couldn't decrypt the data; since anything the server can do, the attacker could too. The answer to this problems is asymmetric encryption, specifically public-key cryptography.

  1. You generate a public-private key pair on your own computer.
  2. You keep the private key private; do not let it leave your personal computer.
  3. You have your server encrypt data with your public key and write it to a file.
  4. Whenever you want to look at the data, you download the file and decrypt it with your private key.

The implementation details I'll leave up to the reader.

Note that the attacker in this scenario would be able to obtain a copy of the cypher text; this in itself won't reveal any information to the attacker, and it is generally infeasible to crack (read: brute force) the encryption. However, it is theoretically possible to brute force the encryption, and implementation mistakes on your part may make that even more feasible.