简体   繁体   中英

PHP Query/Compare user input and aes encrypted data in MySQL

I am trying to find the proper way to query a MySQL table via PHP, with fields in a table that were AES encrypted. I have a login form that grabs last_name plus a few other fields and does a query to compare. Here is a snippit of the relevant structure.

I inserted the data using:

AES_ENCRYPT('".$last_name."','".$encryption_key."') 

I can decrypt, and output the data using:

CAST(AES_DECRYPT(last_name, '$encryption_key') AS CHAR(66)) last_name_decrypt

However I can't get a compare to work. I've tried

$query = "SELECT * from {$tablename} where last_name = AES_ENCRYPT('".$unauth_last_name."','".$encryption_key."')";

Any help or direction is appreciated.

I think you are missing the comparison with the last name obtained by php - probably from a login html form. Assuming that the php variable holding the last name you would like to check against is called $in_last_name , the query may look like sg like as follows:

    $query = "SELECT * from {$tablename} WHERE last_name = AES_ENCRYPT('".$in_last_name."','".$encryption_key."')";

(Obviously, you should sanitize your input or use prepared statements with parameter binding to prevent sql injection attacks. Since I do not know what API you use to connect to MySQL, I cannot suggest an exact solution for this. Anyway, this is beyond the scope of this question.)

The query encrypts the inputted last name (plain text) and checks it against the stored encrypted data. Also, there must be no field alias in the where clause.

Again, using field level encryption this way does not make the data that secure since it relies on the encryption key being secret. Such encryption only makes your life more difficult.

You may want to check out other means of encrypting data within MySQL. Check out MySQL Enterprise Encryption for example, which allows DBAs to manage encrypted data without actually having access to the plain text version. Yes, this is not a free product.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM