MySQL des_encrypt() function

des_encrypt() function

MySQL DES_ENCRYPT() encrypts a string with a key Triple-DES algorithm.

This function works only with Secure Sockets Layer (SSL) if support for SSL is available in MySql configuration.


DES_ENCRYPT(str,[{key_num | key_str}]);


Name Description
str A string which is to be encrypted.
key_num A number from 0 to 9 from DES key file.
key_str A string to encrypt str.

Example: MySQL des_encrypt() function


SELECT DES_ENCRYPT('mytext',5),DES_ENCRYPT('mytext','mypassward');


The above MySQL statement encrypts the string mytext with key number 5; for the second instance of the function, mytext is encrypted with mypassword.

Sample Output:

mysql> SELECT DES_ENCRYPT('mytext',5),DES_ENCRYPT('mytext','mypassward');
| DES_ENCRYPT('mytext',5) | DES_ENCRYPT('mytext','mypassward') |
| …ÿc}æ¤~               | ÿ]ï×ñ”Å                          | 
1 row in set (0.00 sec)

PHP script:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>php mysql examples</title>
echo "<h2>Encrypting using DES_ENCRYPT : </h2>";
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
echo "<tr style='font-weight: bold;'>";
echo "<td width='100' align='center'>DES_ENCRYPT('mytext',5)</td><td width='100' align='center'>DES_ENCRYPT('mytext','mypassward')</td>";
echo "</tr>";
$result = mysql_query("SELECT DES_ENCRYPT('mytext',5),DES_ENCRYPT('mytext','mypassward')");
echo "<tr>";
echo "<td align='center' width='200'>" . $row["DES_ENCRYPT('mytext',5)"] . "</td>";
echo "<td align='center' width='200'>" . $row["DES_ENCRYPT('mytext','mypassward')"] . "</td>";
echo "</tr>";
echo "</table>";

View the example in browser

Example : MySQL des_encrypt() function using table

Sample table: testtable


INSERT INTO testtable


The above MySQL statement will insert encrypted data into table 'testtable'.

Sample Output:

mysql> INSERT INTO testtable
    -> VALUE(DES_ENCRYPT('mydesencrypttext','mydespassw'));
Query OK, 1 row affected (0.00 sec)

Online Practice Editor:

Previous: DES_DECRYPT()
Next: ENCODE()

Follow us on Facebook and Twitter for latest update.

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook