This article is half-done without your Comment! *** Please share your thoughts via Comment ***
This is going to be one of most important article for the MySQL community because I am going to share, what should be our best practice to store encrypted passwords into MySQL Database Server.
The MySQL provides different algorithm and function to encrypt and decrypt password data or any other sensitive information so that no one can access it in plain text format.
For different Encryption and Compression functions you can visit this MySQL Developer official site.
Generally, people are using MD5 and SHA algorithm for password encryption, but both are easy to break and vulnerable, so we should not use this in our general practice.
We should also not use PASSWORD() function because it is used by the authentication system in MySQL Server.
Advanced Encryption Standard Algorithm (AES):
This is one of the important encryption algorithm and it is highly secure because it encrypts the string using the encryption key string and returns an encrypted binary string output.
MySQL provides AES_ENCRYPT() to encrypt the string in binary format and AES_DECRYPT() to decrypt the string in plain text.
The only one problem is, we should hide the key value for security purpose by setting object level permission or we can create a view to hide the encryption key value.
You can create BINARY or BLOB data type to store AES encrypted password.
Below is a small demonstration on this:
The syntax:
1 2 |
AES_ENCRYPT(str,key_str) AES_DECRYPT(crypt_str,key_str) |
First, create a table with sample data:
1 2 3 4 5 6 7 8 9 10 |
CREATE TABLE tbl_AESPassword ( ID INTEGER ,UserPassword BLOB ); INSERT INTO tbl_AESPassword VALUES (1,AES_ENCRYPT('Anvesh','8')) ,(2,AES_ENCRYPT('Patel','88')); |
SELECT first row by comparing password using defined encryption key:
1 2 3 4 5 6 7 8 |
SELECT * FROM tbl_AESPassword WHERE UserPassword = AES_ENCRYPT('Anvesh','8') -- Result: Returned only first record. ID | UserPassword --------------------------- 1 | BLOB |
To DECRYPT the password into plain text:
1 2 3 4 5 6 7 8 |
mysql> SELECT AES_DECRYPT(AES_ENCRYPT('Anvesh','8'),'8'); +--------------------------------------------+ | AES_DECRYPT(AES_ENCRYPT('Anvesh','8'),'8') | +--------------------------------------------+ | Anvesh | +--------------------------------------------+ 1 row in set (0.00 sec) |