Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL SELECT WHERE LIKE WITH AES_ENCRYPT

How would I perform a Mysql SELECT with WHERE and LIKE serach if field is AES_ENCYPTED?

Example:

SELECT AES_DECRYPT(place,'"+salt+"'),AES_DECRYPT(web_address,'"+salt+"') 
FROM access 
WHERE place= LIKE '%(AES_ENCRYPT('"+searchStr+"','"+salt+"'))',%')

Basically, perform a search on an encrypted column with the LIKE wildcard on both ends of the $searchStr

like image 462
user963206 Avatar asked Sep 30 '11 16:09

user963206


People also ask

How to use AES DECRYPT in MySQL?

The MySQL AES_DECRYPT function returns the original string after decrypting an encrypted string. It uses AES(Advanced Encryption Standard) algorithm to perform the decryption. The AES_DECRYPT function returns the decrypted string or NULL if it detects invalid data.

How to ENCRYPT text in MySQL?

The MySQL AES_ENCRYPT function is used for encrypting a string using Advanced Encryption Standard (AES) algorithm. The MySQL AES_ENCRYPT function encodes the data with 128 bits key length but it can be extended up to 256 bits key length. It encrypts a string and returns a binary string.

How can we encrypt and decrypt a data presented in a table using mysql?

Use AES_ENCRYPT (),AES_DECRYPT() functions in mysql for encryption and decryption.


2 Answers

You can't search on an encrypted column without first decrypting it.

You'll need to do WHERE AES_DECRYPT(like, salt) LIKE '%something%' but it's going to be quite slow.

like image 193
ceejayoz Avatar answered Sep 20 '22 23:09

ceejayoz


I have been looking for a simple way to use the SELECT LIKE for an AES_ENCRYPTED field with MySQL. The one that works the best is:

SELECT * FROM table 
WHERE CONVERT(AES_DECRYPT(`haystack`,'key') USING utf8) LIKE '%needle%'

I have tested this on MySQL 5 using PHP 5.

This runs very well when processing several thousand rows, but may not be ideal for very large tables due to the decryption and conversion.

This is the basic PHP code:

$key   = md5("yourchosenkey".$salt);     
$query = "SELECT * FROM ".$tableName." ". 
         "WHERE CONVERT(AES_DECRYPT(`haystack`,'".$key."') USING utf8) ".
         "LIKE '%".addslashes($needle)."%'";
like image 30
FedWeb Avatar answered Sep 18 '22 23:09

FedWeb