How to Use MySQL's AES_ENCRYPT and AES_DECRYPT to Store Passwords in a Database
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.
View the code here.
1: 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.
$key = 'ASKSDFNSDFKEISDJAHDLDSDF1235UUUiidfsdf';
2: Encrypt the password
mysql_query("INSERT INTO users (user_first, user_last, user_password) VALUES ('".$_POST['first']."','".$_POST['last']."',AES_ENCRYPT($_POST['password'],$key))");
3: Decrypt the password
Now, to display the decrypted password, you'll need a query similar to the one below:
$password = mysql_fetch_row(mysql_query("SELECT AES_DECRYPT(user_password,'$key') FROM users WHERE user_id = 4"));
echo $password[0];
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.
Categories
· Mobile (1) · Projects (50) · Tutorials (12) · PHP (12) · jQuery (5) · MySQL (4)
View by date
· View All · February 2012 · January 2012 · December 2011 · November 2011 · October 2011 · September 2011 · July 2011 · June 2011 · May 2011 · April 2011 · March 2011 · February 2011 · January 2011 · December 2010 · November 2010 · October 2010 · September 2010 · July 2010 · May 2010 · April 2010 · February 2010 · January 2010 · November 2009 · August 2009 · July 2009 · May 2009 · April 2009 · March 2009 · February 2009 · January 2009 · December 2008 · November 2008 · October 2008 · June 2008 · May 2008 · April 2008