mysql数据加密aes_encrypt()和aes_decrypt()

Here's the scenario.  You are building a custom member login area to a website.  You need to store the user's name, email address and a password.  The name and email can be stored in 'plain text', but for added security, you want to store the password in an encrypted format (in case someone steals the database somehow, or just for your users' peace of mind).

This mini-tutorial assumes you already know how to connect to your database and work with php/mysql.   

The benefit of using AES_ENCRYPT and AES_DECRYPT is that you can both encrypt the password, then decrypt the password whenever necessary.  This is helpful if you ever want to display the password to the user in an email, or if you're encrypting other account information that you need to display.  

 

  The Key
For this to work, you must define a "key" to use when encrypting and decrypting the information from the database.  It would be best to store this key somewhere on your server outside of the main directory in which you're working.  This key can be whatever you want it to be, but you must also reference the same key during encrypting and decryption.

 

 

 

1. Create a test table, encrypt the userdata field when storing:
CREATE TABLE UserTest (
  userID int unsigned not null auto_increment,
  user_name varchar(30) NOT NULL,
  userdata blob,
  PRIMARY KEY  (userID)
);

2. Encrypt the userdata, it need to define a "key" to use when encrypting and
decrypting the information from the database, here is 'encrypt_key'.
INSERT INTO UserTest(user_name,userdata)
VALUES ('TestName', AES_ENCRYPT('salary_data','encrypt_key'));

3. Decrypt the userdata when we need to display the original, unencrypted
value.
SELECT AES_DECRYPT(userdata,'encrypt_key') FROM UserTest
WHERE user_name='TestName';
So, using AES_ENCRYPT and AES_DECRYPT can be very useful when you need to store encrypted information in a database as well as display the original, unencrypted information.  Remember, you must use a 'key' in order to "unlock" and display the encrypted information.

你可能感兴趣的:(mysql,PHP,Security)