Question

In PHP, i have a action.php page, i have a string which is stored into a variable

$myString = "Foo Bar";

I'm encrypting this string using AES256 with the following function :

function aes256Encrypt($key, $data) {

if(32 !== strlen($key)) $key = hash('SHA256', $key, true);

$padding = 16 - (strlen($data) % 16);

$data .= str_repeat(chr($padding), $padding);

return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC,    str_repeat("\0", 16));

}

And before inserting data to MySQL database, I'm using mysql_real_escape_string() to the encrypted string before inserting it to DB

In my knowledge, the mysql_real_escape_string() function adds \ before the charachters that need to be escaped !

In the other hand, i need to get the data back from MySQL and decrypt it using this function :

  function aes256Decrypt($key, $data) {

  if(32 !== strlen($key)) $key = hash('SHA256', $key, true);

  $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC,   str_repeat("\0", 16));

  $padding = ord($data[strlen($data) - 1]);

  return substr($data, 0, -$padding);

  }

Everything is OK, when i decrypt the string that i get from db, i get the correct string back, but I get really confused on how could this work correctly without un-escaping the string back after getting it from DB ?

Was it helpful?

Solution

First of all, you should really switch from using mysql_* to either PDO or mysqli and use properly parameterized statements. Then, you avoid calls to mysql_real_escape_string altogether.

The escaping concept is very broad in programming, and it applies here. Say you want to store someone's name to the DB: Coryn O'Driscoll. This is not even malicious, but this query will fail:

INSERT INTO Names VALUES ('Coryn O'Driscoll')

You have an unclosed string.

mysql_real_escape_string converts this to ('Coryn O\'Driscoll'). The \' signals to mysql that the apostrophe is not a part of the syntax of the query but actuall part of the scalar value to insert. It is actually inserted as Coryn O'Driscoll. This is why you don't have to remove any backslashes from it when you select it again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top