I created user table
CREATE TABLE `user` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
`first_name` VARBINARY(100) NULL ,
`address` VARBINARY(200) NOT N
According to the Manual:
AES_ENCRYPT() encrypts a string and returns a binary string. AES_DECRYPT() decrypts the encrypted string and returns the original string.
I don't know why it is still returning a binary string in your case. Anyway, try this:
SELECT *,
CAST(AES_DECRYPT(first_name, 'usa2010') AS CHAR(50)) first_name_decrypt
FROM user
And use first_name_decrypt
instead of first_name
.
From mysql command line client there is no need to use CAST
:
mysql> SELECT AES_DECRYPT(AES_ENCRYPT('admin','abc'),'abc');
+-----------------------------------------------+
| AES_DECRYPT(AES_ENCRYPT('admin','abc'),'abc') |
+-----------------------------------------------+
| admin |
+-----------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT CAST(AES_DECRYPT(AES_ENCRYPT('admin','abc'),'abc') AS CHAR (50));
+------------------------------------------------------------------+
| CAST(AES_DECRYPT(AES_ENCRYPT('admin','abc'),'abc') AS CHAR (50)) |
+------------------------------------------------------------------+
| admin |
+------------------------------------------------------------------+
1 row in set (0.02 sec)
As you can see using cast in command line is little bit slower. But I have noticed that if you use some tools like phpmyadmin, then you need to use CAST
, otherwise result will be wrong.
I had the same issue, turns out I had my column data type set as VARCHAR when I encrypted the data and when I switched over to MEDIUMTEXT, it wouldn't return anything else than a BLOB.
Quoting a part from dev.mysql:
Many encryption and compression functions return strings for which the result might contain arbitrary byte values. If you want to store these results, use a column with a VARBINARY or BLOB binary string data type. This will avoid potential problems with trailing space removal or character set conversion that would change data values, such as may occur if you use a nonbinary string data type (CHAR, VARCHAR, TEXT).
Switching to a supported column type worked for me.
if (isset($_POST['user_name']) and isset($_POST['user_password'])){
$user_name = $_POST['user_name'];
$user_password = $_POST['user_password'];
$query = "SELECT * FROM `user_tbl` WHERE user_name='$user_name' and AES_DECRYPT(user_password , '@ert') = '$user_password'";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);