I am experimenting with creating a simple message system (PHP) page that uses a MySQL table to store the entries. The rough outline of the columns I'll use in the table are:
msg_id (primary key, auto_increment)
user_id (foreign key pointing to the user who created the message)
time (a DATETIME entry to provide msg timestamps)
msg (a VARCHAR containing the msg)
accessable (just an int(1), 0 means no one except the user himself can read the msg, and 1 means others can read it)
What I'm wondering is, what's the best way to encrypt the msg field so prying eyes can't read it (let's say, by opening the mysql CLI or phpMyAdmin and just read the value stored in a row)?
If "accessable" is set to 0, then only the user him/herself should be able to read it (by accessing some PHP page), but if set to 1, everyone else should be able to read it as well. I don't know how to tackle this, so any help is very appreciated!
解决方案
Look here for list of possible encryption functions:
You can create trigger for update and check there field accessable. Something like that:
CREATE TRIGGER crypt_trg BEFORE UPDATE ON table FOR EACH ROW
BEGIN
IF new.accessable = 0 THEN
SET new.msg := ENCRYPT(new.msg, 'key');
ELSE
SET new.msg := DECRYPT(new.msg, 'key');
END IF;
END;
You also can update all existing records in you table with this query:
UPDATE table SET msg = IF(accessable = 0, ENCRYPT(msg, 'key'), DECRYPT(msg, 'key'));
So you can select records for you PHP code:
SELECT msg_id, user_id, time, IF(accessable = 0, DECRYPT(msg, 'key'), msg) msg
FROM table
UPD. Also here was similar question: